From efd52dae7d92e5fc895004a5f4ea783eaf8b7514 Mon Sep 17 00:00:00 2001 From: attilavs2 Date: Sat, 12 Apr 2025 13:57:32 +0200 Subject: [PATCH] Petit fix dans l'interface lua --- script/test.lua | 7 ++++++- src/lua_inter.c | 41 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/script/test.lua b/script/test.lua index 4c359ee..824dc05 100644 --- a/script/test.lua +++ b/script/test.lua @@ -11,7 +11,12 @@ machine.pos.x = 50 machine.storage[0] = 1 function on_tick(game) - + -- Ceci va drainer la sortie de la machine 2 + -- (Le premier fourneau) + local mach = get_machine_from_id(2) + if mach.storage[4] > 0 then + mach.storage[4] = mach.storage[4]-1 + end end function on_frame(game) diff --git a/src/lua_inter.c b/src/lua_inter.c index 46eae81..63ffbc3 100644 --- a/src/lua_inter.c +++ b/src/lua_inter.c @@ -52,6 +52,32 @@ static int lua_V2d_newindex(lua_State *L){ return 0; } +static int lua_storage_index(lua_State *L){ + uint8_t **ptr = luaL_checkudata(L, 1, "Storage"); + uint8_t *storage = *ptr; + int pos = luaL_checkinteger(L, 2); + if(pos >= 0 && pos < 5){ + lua_pushinteger(L, storage[pos]); + return 1; + } + else + return 0; +} + +static int lua_storage_newindex(lua_State *L){ + uint8_t **ptr = luaL_checkudata(L, 1, "Storage"); + uint8_t *storage = *ptr; + int pos = luaL_checkinteger(L, 2); + int val = luaL_checkinteger(L, 3); + if(pos >= 0 && pos < 5){ + storage[pos] = val; + } + else + return luaL_error(L, "Invalid index for Storage"); + + return 0; +} + static int lua_machine_index(lua_State *L){ void **ptr = luaL_checkudata(L, 1, "Machine"); Machine *mach = *ptr; @@ -74,11 +100,10 @@ static int lua_machine_index(lua_State *L){ ret = mach->active; } else if(!strcmp(name, "storage")){ - lua_createtable(L, 5, 0); - for(int i = 0; i < 5; i++){ - lua_pushinteger(L, mach->storage[i]); - lua_seti(L, -2, i); - } + uint8_t **ptr = lua_newuserdatauv(L, sizeof(void*), 0); + *ptr = mach->storage; + luaL_newmetatable(L, "Storage"); + lua_setmetatable(L, -2); return 1; } else if(!strcmp(name, "id")){ @@ -248,6 +273,12 @@ void lua_mt_init(lua_State *L){ lua_setfield(L, -2, "__index"); lua_pushcfunction(L, lua_V2d_newindex); lua_setfield(L, -2, "__newindex"); + + luaL_newmetatable(L, "Storage"); + lua_pushcfunction(L, lua_storage_index); + lua_setfield(L, -2, "__index"); + lua_pushcfunction(L, lua_storage_newindex); + lua_setfield(L, -2, "__newindex"); } void script_init(Game *game){