Eval function in LUA 5.1
Asked Answered
C

1

8

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')
Companionate answered 7/9, 2018 at 22:46 Comment(0)
D
10

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

Datary answered 7/9, 2018 at 22:52 Comment(8)
When trying your code on the official LUA interpreter I got the result : 'input:2: attempt to call a nil value (global 'loadstring')' ; Is there something I still miss ?Companionate
Which version of Lua are you using? lua -v on the command line will tell you.Datary
The Lua version is 5.1.4Companionate
I added information about Lua versions 5.2+. The online demo that you linked to is, at least at this moment, version 5.3: print(_VERSION). loadstring works with no set up in 5.1.4.Datary
Ok was trying it on the official interpreter which was 5.3.5, but my version is 5.1.4, so actually it was good with loadsting. Thanks !Companionate
@NicolBolas I don't think dostring is available from the Lua side (though dofile is): lua.org/manual/5.3/manual.html#luaL_dostringDatary
it's very likely to cause security and stability problems in real world systems What are the problems you are talking about?Gilded
@EgorSkriptunoff Sanitizing code is a really hard problem; if there's any chance of any bit of user input going into loadstring, you likely have made a mistake. If it's possible to safely sanitize the user input, loadstring is probably not necessary (a simple DSL or just table lookups are likely sufficient). In any case, if you have loadstring doing anything important, it's completely invisible, because it's a string and not code (and likely invisibly affecting global variables).Datary

© 2022 - 2024 — McMap. All rights reserved.