2

I have a string, something like:

local func = "1 == 3"

How can I convert this into a function to execute and get a result from within another function? Like:

function CheckFunc(func)
 local ret = functon() return func end

 return ret
end

3 Answers 3

8

loadstring() is the function You're looking for :)

In your case it would be used like: local func = loadstring("return (1==3)")

Sign up to request clarification or add additional context in comments.

Comments

6
local func = "1 == 3"

function wrap(s)
    return loadstring("(function() return "..s.." end)()")
end

funcWrapped = wrap(func)

if funcWrapped() then
    print "One eqauls Three"
else
    print "One doesn't equal Three"
end

Would output

One doesn't equal Three

NOTE: You should use @Kamiccolo's loadstring in place of mine within wrap

Comments

4

In Lua 5.1, you can use loadstring, as the other answers have already said:

local func = loadstring("return(1==3)")

In Lua 5.2, it's better to use load

local func = load("return(1==3)")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.