lua基础(sh向lua传递参数arg)

最近将lua作为一种独立的脚本语言来制作一些小工具。在使用过程中发现了一个一直被忽视的知识点,全局变量arg。
任务:通过sh脚本调用lua。
问题:需要通过命令模式对lua脚本传递参数
解决方法:lua全局变量arg
参考文献:lua手册
6 - Lua Stand-alone
Although Lua has been designed as an extension language, to be embedded in a host C program, it is also frequently used as a stand-alone language. An interpreter for Lua as a stand-alone language, called simply lua, is provided with the standard distribution. The stand-alone interpreter includes all standard libraries, including the debug library. Its usage is:

 lua [options] [script [args]]

The options are:

-e stat: executes string stat;
-l mod: “requires” mod;
-i: enters interactive mode after running script;
-v: prints version information;
–: stops handling options;
-: executes stdin as a file and stops handling options.
After handling its options, lua runs the given script, passing to it the given args as string arguments. When called without arguments, lua behaves as lua -v -i when the standard input (stdin) is a terminal, and as lua - otherwise.

Before running any argument, the interpreter checks for an environment variable LUA_INIT. If its format is @filename, then lua executes the file. Otherwise, lua executes the string itself.

All options are handled in order, except -i. For instance, an invocation like

 $ lua -e'a=1' -e 'print(a)' script.lua

will first set a to 1, then print the value of a (which is ‘1’), and finally run the file script.lua with no arguments. (Here $ is the shell prompt. Your prompt may be different.)

Before starting to run the script, lua collects all arguments in the command line in a global table called arg. The script name is stored at index 0, the first argument after the script name goes to index 1, and so on. Any arguments before the script name (that is, the interpreter name plus the options) go to negative indices. For instance, in the call

 $ lua -la b.lua t1 t2

the interpreter first runs the file a.lua, then creates a table

 arg = { [-2] = "lua", [-1] = "-la",
         [0] = "b.lua",
         [1] = "t1", [2] = "t2" }

and finally runs the file b.lua. The script is called with arg[1], arg[2], ··· as arguments; it can also access these arguments with the vararg expression ‘…’.

sh执行lua,使用lua命令模式,以上官方说明很清楚,在脚本执行的中会将命令解析并存入全局变量arg中,通过全局变量实现参数传递。

测试脚本test.lua


function test()
print("arg[-3]=" , arg[-3])  
print("arg[-2]=" , arg[-2])  
print("arg[-1]=" , arg[-1])  
print("arg[0]=" , arg[0])  
print("arg[1]=" , arg[1])  
print("arg[2]=" , arg[2])  
end

test()

测试结果:
twwkdeMBP:lua twwk$ lua test.lua 12 13
arg[-3]= nil
arg[-2]= nil
arg[-1]= lua
arg[0]= test.lua
arg[1]= 12
arg[2]= 13

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值