lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Jim zhang once stated:
> Code to be test:
> struct A
> {
>    int a,
>    int b
> };
>  
> int sum ( struct A * s)
> {
>    retunr s->a+s->b;
> }
>  
> How could I construct a struct A object in lua scripts, and pass the pointer of this struct into sum() to test it?

  Well, here's one way:

------- Lua -----------

sum = require "sum"

x = { a = 1 , b = 2 }

y = sum(x)
print(y)

z = sum { a = 2 , b = 3 }
print(z)

/********* C *******************/

#include <lua.h>
#include <lauxlib.h>

static int sumlua(lua_State *L)
{
  struct A;
  int    x;

  lua_getfield(L,1,"a");
  lua_getfield(L,1,"b");

  A.a = luaL_checkinteger(L,-2);
  A.b = luaL_checkinteger(L,-1);
  x   = sum(&A);
  lua_pushinteger(L,x);
  return 1;
}

int luaopen_sum(lua_State *L)
{
  lua_pushcfunction(L,sumlua);
  return 1;
}

Compile the C code into the appropriate shared object for your platform, and
then the Lua code will be able to load the C interface.

  -spc