简体   繁体   中英

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')

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+.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM