1

I have this C struct:

typedef struct { double x, y; } point_t;    

and I need to send a point_t variable to Lua and change its values and then return it to C. The first problem that I have is to cast it in Lua. How can it be done ?

main.c

point_t ponto;

ponto.x = 0; ponto.y = 0;

lua_getglobal(L, "jit"); //Get variavel with function
lua_pushlightuserdata(L, &ponto);
lua_pcall(L, 1, 1, 0);

point_t *pontop = (point_t*)lua_touserdata(L, -1);

test.lua

 jit = function(num)
    local ffi = require("ffi")
    ffi.cdef[[
    typedef struct { double x, y; } point_t;
    ]]

    local point
    local mt = {}
    point = ffi.metatype("point_t", mt)

    local a = point(3, 4)
    print(a.x, a.y)
    b = ffi.cast("point_t*",num)
    b.x = 10
    b.y = 20
    return b
end

The local variable a is created with point_t type, how can I cast b to use it like a ?

MrFabio
  • 586
  • 2
  • 15
  • 31
  • Don't mix lua C API with luajit's FFI mechanism. See http://stackoverflow.com/a/18822678/234175 – greatwolf Feb 09 '15 at 05:14
  • yes, I came up with that question. Is it even possible ? – MrFabio Feb 09 '15 at 15:45
  • For your case above, you can probably get away with `return num`. The main thing is after doing `ffi.cast`, `b` is now a 'cdata' and ffi doesn't provide a way to back cast into a userdata. The lua-api doesn't understand 'cdata'. – greatwolf Feb 09 '15 at 23:02
  • but it's important to change values in the struct, that's the point of all this. – MrFabio Feb 09 '15 at 23:45
  • `b` and `num` both refer to the same object. Changing the fields through `b` will be reflected in `num`. Doing a `print(b, num)` for example, will show the same address but one is treated as 'cdata' while the other is 'userdata'. – greatwolf Feb 10 '15 at 00:06
  • but lua doesn't know how to access the fields inside `num` in order to change it, it's just a pointer – MrFabio Feb 10 '15 at 01:51
  • But you're not accessing the fields through `num`, you're doing it through `b`. The `b = ffi.cast("point_t *", num)` is sort of like `lua_touserdata` but from lua space made possible by luajit's ffi. Changing the fields using `b` will automatically change it in `num` also since they're pointing to the same underlying object. I'm not sure where the confusion is. – greatwolf Feb 10 '15 at 03:51

0 Answers0