lua-users home
lua-l archive

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


If I care more about the object passing in, and change the code as following:
 
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);
A.a = 2*A.a;
A.b = 2*A.b;
---- [[if I want to passing the updated object A back to lua
 something like  lua_pushinteger(L,A);  what should I do? ]]
 
--- to push A back to lua
  return 1;
}
 
What would I do?
Thanks,
 
Jim
 
From: Sean Conner <sean@conman.org>
To: Jim zhang <jimzhang02@yahoo.com>; Lua mailing list <lua-l@lists.lua.org>
Sent: Thursday, March 7, 2013 12:54 AM
Subject: Re: how to construct sturct object in lua

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