Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Struggling with calling lua functions from the command line

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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:

  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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading