Reputation: 1
I'm trying to make a scripting tutorial for a friend (I'm not too good at it myself but okay) and I'm trying to make it so the input creates an actual line of code that does what they typed. EG:
Input: print("hello")
hello
I understand this is what a console does, but is there any way I can do it with Lua?
Thanks.
Upvotes: 0
Views: 240
Reputation: 13
One way to do this would be using the loadstring function.
Example:
run = loadstring("print('Hello World!'")
run()
Output:
Hello World!
Upvotes: 0
Reputation: 2715
load (ld [, source [, mode [, env]]])
Loads a chunk.
If ld is a string, the chunk is this string.
...
If there are no syntactic errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message.
local input = [[
local args = {...}
print(args[1], args[3]) -- 42 1
return args[1] + args[2], args[2] + args[3]
]]
print(load(input)(42, 99, 1)) -- 141 100
As you can see, the input has access to globals, you can pass values into his code and get the returns.
Upvotes: 1
Reputation: 26742
just run the lua command to get a lua "REPL":
$ ./lua
Lua 5.3.1 Copyright (C) 1994-2015 Lua.org, PUC-Rio
> print("hello")
hello
>
Upvotes: 2