Reputation: 945
I use luaVM in another programming language (Vala) and want to pass the code from vala to lua so that lua returns the result of executing this code as a string.
> s2="print (5+5)"
> s2
print (5+5)
> loadstring(s2)
function: 0x55834153f080
> func = loadstring(s2)
> func()
10
tried a lot of things, but I did not succeed, that is, I need instead of 10 was a variable of type string containing 10. So I could do vm.to_string(-1) of Vala and to obtain "10"
Upvotes: 4
Views: 1761
Reputation: 5031
As Egor stated you can cast your result to a string before returning it using tostring
.
I would also add you may want to use dostring
not loadstring
.
A load
function in lua means to compile and not run the chunk, instead it returns a function when called will run the chunk.(loadfile
, loadstring
)
A do
function will compile and run the contents.(dofile
, dostring
)
The details can be found here: Lua: 8 – Compilation, Execution, and Errors
Like dofile, loadfile also loads a Lua chunk from a file, but it does not run the chunk. Instead, it only compiles the chunk and returns the compiled chunk as a function.
This section speak more directly to loadfile
but the page covers loadstring
.
if dostring
is not defined it can be like so:
function dostring(s)
return assert(loadstring(s))()
end
If you are using a version of lua later then 5.1 loadstring
becomes load
Upvotes: 4