Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting command line parameters in Lua interpreter

Tags:

lua

How can I call a function in Lua? I am new to Lua and couldn't find how to do something very simple. I write a test.lua and make it executable. Inside I put this:

function Double(n)
 return 2*n
end

print(Double(15))

If I call test.lua, it returns 30, ok.

Now I remove the print line and want to be able to call the function with something like:

test.lua 15

It doesn't work. How can I call the function from the command line or from the Lua shell without hard coding the first argument?

like image 218
Cascalho Avatar asked Dec 05 '25 13:12

Cascalho


1 Answers

You can pass an argument to the script which will appear in the arg global.

e.g.

function Double(n)
 return 2*n
end

print(Double(arg[1]))

http://www.lua.org/pil/1.4.html

like image 144
Nick Van Brunt Avatar answered Dec 08 '25 08:12

Nick Van Brunt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!