Struggling with calling lua functions from the command line

Viewed 87

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
2 Answers

That is to be expected. What's going on here:

  1. You're executing the file specified by the first argument, printstuff.lua, which will leave a function printStuff in the global table _G.
  2. You're indexing the global table with the second argument, printStuff, obtaining that function
  3. 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 variable returned. The function printStuff doesn't return anything (there's no return in there, and even if there was, print doesn't return anything either), so you're assigning nil to returned.
  4. You're printing returned, which is nil

Side note: I'd use the vararg ... instead of the arg table for improved readability:

local file, func, param = ...
dofile(file); print(func(param))

Why not simply...

-- xlua.lua
-- Example: lua xlua.lua os date "%H:%M:%S"
-- Or: lua xlua.lua _G print "Hello World"
-- Or: lua xlua.lua dofile /path/to/someusefull.lua "Arg for someusefull.lua"

local result = _G[arg[1]][arg[2]](arg[3])

-- 5. Only put out whats not nil
if (result ~= nil) then
  print(result)
end
Related