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')
Eli O.
  • 1,543
  • 3
  • 18
  • 27

1 Answers1

9

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

Curtis Fenner
  • 1,382
  • 1
  • 9
  • 18
  • 2
    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 ? – Eli O. Sep 07 '18 at 22:57
  • Which version of Lua are you using? `lua -v` on the command line will tell you. – Curtis Fenner Sep 07 '18 at 23:00
  • The Lua version is 5.1.4 – Eli O. Sep 07 '18 at 23:02
  • 1
    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. – Curtis Fenner Sep 07 '18 at 23:03
  • 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 ! – Eli O. Sep 07 '18 at 23:05
  • @NicolBolas I don't think `dostring` is available from the Lua side (though `dofile` is): https://www.lua.org/manual/5.3/manual.html#luaL_dostring – Curtis Fenner Sep 08 '18 at 03:50
  • `it's very likely to cause security and stability problems in real world systems` What are the problems you are talking about? – Egor Skriptunoff Sep 08 '18 at 04:09
  • @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). – Curtis Fenner Sep 08 '18 at 17:45