access to lua arrays from within C code

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

access to lua arrays from within C code

Norman Ramsey-3
I have a C function that expects char *argv[] as an argument.
The natural representation for argv in Lua would be as a table
with elements 1, 2, 3, etc.

What is the recommended method of getting access to the array elements
from within my C code?

Norman

Reply | Threaded
Open this post in threaded view
|

Re: access to lua arrays from within C code

Luiz Henrique de Figueiredo
>I have a C function that expects char *argv[] as an argument.
>The natural representation for argv in Lua would be as a table
>with elements 1, 2, 3, etc.
>
>What is the recommended method of getting access to the array elements
>from within my C code?

The easiest solution is something like:

/* CAUTION: untested code ahead */

 lua_Object t=lua_getparam(1);

 for (i=0; i<N; i++)
 {
  lua_Object v;
  lua_beginblock();
  lua_pushobject(t);
  lua_pushnumber(i);
  v=lua_gettable()
  if (v==LUA_NOOBJECT || lua_isnil(v)) break;
  argv[i]=lua_getnumber(v);
  lua_endblock();
 }

 argc=i;
 myfunction(argc,argv);

Another solution is to use "call" in lua:

 function myfunction(t)
	 call(actual_myfunction,t)
 end

where the C function "myfunction" is registered in Lua as "actual_myfunction".

With this code in place, you can access the array elements in C as if they
were arguments:

 for (i=0; i<N; i++)
 {
  lua_Object v;
  v=lua_param(i)
  if (v==LUA_NOOBJECT || lua_isnil(v)) break;
  argv[i]=lua_getnumber(v);
 }

Hope this helps.
--lhf

Reply | Threaded
Open this post in threaded view
|

Re: access to lua arrays from within C code

Norman Ramsey-3
 > >I have a C function that expects char *argv[] as an argument.
 > >The natural representation for argv in Lua would be as a table
 > >with elements 1, 2, 3, etc.
 > >
 > >What is the recommended method of getting access to the array elements
 > >from within my C code?

 >  for (i=0; i<N; i++)
 >  {
 >   lua_Object v;
 >   v=lua_param(i)
 >   if (v==LUA_NOOBJECT || lua_isnil(v)) break;
 >   argv[i]=lua_getnumber(v);
 >  }

I must not have stated my question very carefully.
I have something like this for treating a table as an array:

<<print the elements in [[list]] as indexed by small integers>>=
for (i = 1; ; i++) {
  lua_Object o;
  lua_pushobject(list);
  lua_pushnumber((double)i);
  o = lua_getsubscript();
  if (lua_isnil(o)) break;
  s = lua_getstring(o);
  if (!s) lua_error("argument is not a string");
  printf("  %s\n", s);
}


but there is no guarantee that a table I am passed actually represents
an array.  I can't see how to find the number of non-nil entries in a
table, which is also awkward if I want to use tables to represent
sequences----it becomes difficult to write put, get, or append.

Norman