views:

88

answers:

1

I am looking for sample code in C which reads Lua command line arguments. Any help?

+4  A: 

The Lua interpreter is designed to be embedded withing a hosting application. It is that application's responsibility to pass any command line arguments (or the application's equivalent) to the script by some appropriate mechanism.

When used as a free-standing language, the hosting application is the executable lua, implemented by lua.c in the Lua source distribution.

When it begins, lua bundles any and all command line arguments into the global varaible arg in the form of an array. arg[0] contains the name of the script file being executed, and arg[1] and later contain any arguments passed to that script on the command line. It also stores the balance of the command line at negative indices in the arg table. For the command lua sample.lua a b c then the array is constructed as if the assignment

arg = { [-1]="lua", [0]="sample.lua", "a", "b", "c" }

was performed before the script is executed. This assignment is performed by the function getargs(), which also leaves the script arguments on the Lua stack so that the script can also access them as variadic arguments to the script's top level function via the ... keyword.

If any module used from a script needs to access the command line arguments, then it would most likely do that from the global arg table. That would hold whether the module were written in C or Lua. Access to the global arg requires that the module's environment hasn't been changed to prevent access to globals.

I've left open the important overall design question of whether or not it is good design to allow a module to depend on the command line arguments. I can see that a module that provides argument parsing might want to do things that way, but even then I would recommend that the option parser be passed the argments by its caller rather than read them directly from the global. That makes it easier to also retrieve arguments from an environment variable or from a configuration file, for example.

RBerteig