Page 1 of 1
run a local Lua-code
Posted: Thu Mar 27, 2014 4:43 pm
by Luke100000
I want to add in my game a computer where you can program in Lua. But I have some problems:
1.) how I can run a code, that he doesn't edit important variables of the games and that you can create own variables whitout deleting the old one?
2.) You should only use special functions, not direct functions of love2d.
here is an example how I want it...
Code: Select all
code = "..." --the code string
functions = {...} --special functions like print, computer on/off, ...
ok, errorstring = loadstring(code)
if ok then
ok() --so, now it should have "functions" and his own variables, but how?
else
print(errorstring)
end
Please no unhelpful commends like "Your english is bad!",..., Thanks.
Re: run a local Lua-code
Posted: Thu Mar 27, 2014 5:02 pm
by slime
Maybe look into the
setfenv and
loadstring functions.
Re: run a local Lua-code
Posted: Thu Mar 27, 2014 5:15 pm
by micha
For an example of a game that let's the player program, check out
trainsported. It is make by Germanunkol (on this forum). He solved the programming by letting the player use an external text editor.
Fonts with constant letter width are called
monospaced fonts
Re: run a local Lua-code
Posted: Tue Apr 01, 2014 11:58 am
by Luke100000
I edit my question, maybe you know better what I want now.
For an example of a game that let's the player program, check out trainsported. It is make by Germanunkol (on this forum). He solved the programming by letting the player use an external text editor.
I don´t find the part of the programming which I need...
But this is exactly what I wanted.
Maybe look into the setfenv and loadstring functions.
of course I use loadstring, but I need something too.
If someone knows how it works, please press POSTREPLY.
Re: run a local Lua-code
Posted: Tue Apr 01, 2014 1:52 pm
by Robin
What slime meant is you'd have to use loadstring together with setfenv. Have you looked into [manual]setfenv[/manual]? It's... not very complicated.
Re: run a local Lua-code
Posted: Tue Apr 01, 2014 3:24 pm
by Luke100000
Thank's to everbody! It works! Sorry slime, I thought setfenv is something like loadstring...
I tried it so:
Code: Select all
a = true
env = { }
env.a = true
code = "a = false" --it will set a to false
ok = loadstring(code) --create a function
setfenv(ok, env) --set the enviroment of ok() to env
ok() --run ok
print(a, env.a) --- true, false
setfenv(ok, _G) --set the enviroment of ok() to the standart, called _G
Re: run a local Lua-code
Posted: Tue Apr 01, 2014 4:03 pm
by Robin
I'd leave out that last line, Luke, if you don't use ok later doesn't do anything, and if you do, it does something you don't want.
Re: run a local Lua-code
Posted: Wed Apr 02, 2014 5:17 pm
by Luke100000
Robin wrote:I'd leave out that last line, Luke, if you don't use ok later doesn't do anything, and if you do, it does something you don't want.
I just want to use _G