Search code examples
luaevallua-5.1

Eval function in LUA 5.1


I want to use an eval function in Lua,

Can't make it work. Did not find documentation on it, does Lua even have an eval function ?

Code tried :

a=1
print(a)
eval('print(a)')
eval 'print(a)'

Official Lua demo interpreter : https://www.lua.org/cgi-bin/demo

Output :

1
input:3: attempt to call a nil value (global 'eval')

Solution

  • Lua has the loadstring function, which parses a string and returns a function that would execute that code, provided the given string is a syntactically correct Lua function body.

    a = 1
    local f = loadstring "print(a)"
    f() --> 1
    

    Be wary that functions made with loadstring won't have access to local variables, only global variables. Also, the normal warnings about using eval in other languages apply to Lua too -- it's very likely to cause security and stability problems in real world systems.

    For Lua 5.2+, see Loadstring function replacement in latest version -- it has been replaced by load, which is more permissive in Lua 5.2+.