Browse Source

Option '-l' can give a name for the global variable.

Sintax for this option now is '-l [globname=]modname'.
pull/27/head
Roberto Ierusalimschy 3 years ago
parent
commit
65434b4d1b
  1. 23
      lua.c
  2. 5
      testes/main.lua

23
lua.c

@ -91,7 +91,8 @@ static void print_usage (const char *badoption) {
"Available options are:\n"
" -e stat execute string 'stat'\n"
" -i enter interactive mode after executing 'script'\n"
" -l name require library 'name' into global 'name'\n"
" -l mod require library 'mod' into global 'mod'\n"
" -l g=mod require library 'mod' into global 'g'\n"
" -v show version information\n"
" -E ignore environment variables\n"
" -W turn warnings on\n"
@ -207,16 +208,22 @@ static int dostring (lua_State *L, const char *s, const char *name) {
/*
** Calls 'require(name)' and stores the result in a global variable
** with the given name.
** Receives 'globname[=modname]' and runs 'globname = require(modname)'.
*/
static int dolibrary (lua_State *L, const char *name) {
static int dolibrary (lua_State *L, char *globname) {
int status;
char *modname = strchr(globname, '=');
if (modname == NULL) /* no explicit name? */
modname = globname; /* module name is equal to global name */
else {
*modname = '\0'; /* global name ends here */
modname++; /* module name starts after the '=' */
}
lua_getglobal(L, "require");
lua_pushstring(L, name);
status = docall(L, 1, 1); /* call 'require(name)' */
lua_pushstring(L, modname);
status = docall(L, 1, 1); /* call 'require(modname)' */
if (status == LUA_OK)
lua_setglobal(L, name); /* global[name] = require return */
lua_setglobal(L, globname); /* globname = require(modname) */
return report(L, status);
}
@ -327,7 +334,7 @@ static int runargs (lua_State *L, char **argv, int n) {
switch (option) {
case 'e': case 'l': {
int status;
const char *extra = argv[i] + 2; /* both options need an argument */
char *extra = argv[i] + 2; /* both options need an argument */
if (*extra == '\0') extra = argv[++i];
lua_assert(extra != NULL);
status = (option == 'e')

5
testes/main.lua

@ -190,6 +190,11 @@ prepfile(("print(a); print(_G['%s'].x)"):format(prog), otherprog)
RUN('env LUA_PATH="?;;" lua -l %s -l%s -lstring -l io %s > %s', prog, otherprog, otherprog, out)
checkout("1\n2\n15\n2\n15\n")
-- test explicit global names in -l
prepfile("print(str.upper'alo alo', m.max(10, 20))")
RUN("lua -l 'str=string' '-lm=math' -e 'print(m.sin(0))' %s > %s", prog, out)
checkout("0.0\nALO ALO\t20\n")
-- test 'arg' table
local a = [[
assert(#arg == 3 and arg[1] == 'a' and

Loading…
Cancel
Save