Skip to content

Commit b15fed7

Browse files
committed
Merge branch 'erezgeva-master' into more_argcargv
* erezgeva-master: Add Lua test for argcargv.i Add argcargv.i to Lua
2 parents b88fe49 + 5851eb0 commit b15fed7

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
require("import") -- the import fn
2+
import("argcargvtest") -- import lib
3+
v = argcargvtest
4+
5+
-- catch "undefined" global variables
6+
local env = _ENV -- Lua 5.2
7+
if not env then env = getfenv () end -- Lua 5.1
8+
setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end})
9+
10+
largs = {"hi", "hola", "hello"}
11+
assert(v.mainc(largs) == 3, "bad main typemap")
12+
13+
targs = {"hi", "hola"}
14+
assert(v.mainv(targs, 1) == "hola", "bad main typemap")
15+
16+
targs = {"hi", "hola"}
17+
assert(v.mainv(targs, 1) == "hola", "bad main typemap")
18+
19+
errorVal = 0
20+
function try()
21+
mainv("hello", 1)
22+
errorVal = 1
23+
end
24+
assert(not pcall(try) and errorVal == 0, "bad main typemap")
25+
26+
v.initializeApp(largs)

Lib/lua/argcargv.i

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/* ------------------------------------------------------------
2+
* --- Argc & Argv ---
3+
* ------------------------------------------------------------
4+
*
5+
* Use it as follow:
6+
*
7+
* %apply (int ARGC, char **ARGV) { (size_t argc, const char **argv) }
8+
* extern int mainApp(size_t argc, const char **argv);
9+
*
10+
* then in the lua:
11+
*
12+
* args = { "arg0", "arg1" }
13+
* mainApp(args);
14+
*
15+
* ------------------------------------------------------------ */
16+
17+
%{
18+
SWIGINTERN int SWIG_argv_size(lua_State* L, int index) {
19+
int n=0;
20+
while(1){
21+
lua_rawgeti(L,index,n+1);
22+
if (lua_isnil(L,-1))
23+
break;
24+
++n;
25+
lua_pop(L,1);
26+
}
27+
lua_pop(L,1);
28+
return n;
29+
}
30+
%}
31+
32+
%typemap(in) (int ARGC, char **ARGV) {
33+
if (lua_istable(L,$input)) {
34+
int i, size = SWIG_argv_size(L,$input);
35+
$1 = ($1_ltype) size;
36+
$2 = (char **) malloc((size+1)*sizeof(char *));
37+
for (i = 0; i < size; i++) {
38+
lua_rawgeti(L,$input,i+1);
39+
if (lua_isnil(L,-1))
40+
break;
41+
$2[i] = (char *)lua_tostring(L, -1);
42+
lua_pop(L,1);
43+
}
44+
$2[i]=NULL;
45+
} else {
46+
$1 = 0; $2 = 0;
47+
lua_pushstring(L,"Expecting argv array");
48+
lua_error(L);
49+
}
50+
}
51+
52+
%typemap(typecheck, precedence=SWIG_TYPECHECK_STRING_ARRAY) (int ARGC, char **ARGV) {
53+
$1 = lua_istable(L,$input);
54+
}
55+
56+
%typemap(freearg) (int ARGC, char **ARGV) {
57+
free((char *) $2);
58+
}

0 commit comments

Comments
 (0)