I have the following code:
dofile(arg[1])
function1 = arg[2]
argument = arg[3]
returned = _G[function1](argument)
print(returned)
It is designed to take three command-line arguments and run a function from a file.
So, i run the command lua libs.lua "printStuff.lua" "printStuff" "\"Hello, World\"", and i always end up with this:
"Hello, World"
nil
I don’t understand why i always get "nil".
Here are the contents of printstuff.lua:
function printStuff(stuff)
print(stuff)
end
>Solution :
That is to be expected. What’s going on here:
- You’re executing the file specified by the first argument,
printstuff.lua, which will leave a functionprintStuffin the global table_G. - You’re indexing the global table with the second argument,
printStuff, obtaining that function - You’re calling the function you just obtained with the third command line argument,
"Hello World!", as parameter, which prints it, and storing the result of that in the global variablereturned. The functionprintStuffdoesn’t return anything (there’s noreturnin there, and even if there was,printdoesn’t return anything either), so you’re assigningniltoreturned. - You’re printing
returned, which isnil
Side note: I’d use the vararg ... instead of the arg table for improved readability:
local file, func, param = ...
dofile(file); print(func(param))