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

来源:互联网 发布:服务器安装linux系统 编辑:程序博客网 时间:2024/05/17 00:51

最近将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])  endtest()

测试结果:
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

0 0
原创粉丝点击