1 posts
Posted 06 May 2013 - 02:22 PM
Title: loadstring() problems
When using the loadstring function (in the lua mode) I have following problem:
loadstring("print(\"test\")")() –works perfect
loadstring("shell.run(\"dance\")")() –doesn't work.
Error: attempt to index ? (a nil value)
I can't figure out why it wont work and I dont understadn which value isn't indexed.
I need this code line for rednet which should call specific functions. The String in the loadstring function will then be received by rednet.
hope u can help me^^
1688 posts
Location
'MURICA
Posted 06 May 2013 - 05:11 PM
Before I begin, I thought that it'd be helpful to know that you can use single quotes inside double quotes, and vice versa:
loadstring("shell.run('dance')")
loadstring('shell.run("dance")')
Both are valid and do the same thing. As for your problem, I'm guessing that strings loaded by loadstring() do not have the shell api (and others) defined in their environment. An environment is simply a table containing all of the variables a function can use. This should work:
func = loadstring("shell.run('dance')")
setfenv(func, getfenv())
func()
This basically takes the script's environment and sends it to the string, so it can see all of the different shell functions.
1190 posts
Location
RHIT
Posted 06 May 2013 - 05:13 PM
Edit: Ninja'd, but whatevs.
Also, @Kingdaro, you need to use getfenv(2) because getfenv will only give you the loadstring env.
Loadstring will not give you the shell api as part of the environment. To get it, you could do something like the following:
local load = loadstring([[
local globals = getfenv(2)
globals["shell"]["run"]("rom/programs/dance")
]])--Multiline strings are better for this than the escape operator
load()
1688 posts
Location
'MURICA
Posted 06 May 2013 - 06:21 PM
Using getfenv() without parameters works perfectly fine, I tested before I made the post.
1190 posts
Location
RHIT
Posted 06 May 2013 - 06:47 PM
Using getfenv() without parameters works perfectly fine, I tested before I made the post.
Ah yes, my mistake. You are setting the environment of the loaded function to the global environment from the global environment, whereas I was getting the global environment from within the loadstring.