From 901c6b498c74534c08a879a3829c05ae7a9a21d8 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Christophe=20Thi=C3=A9ry?= Date: Thu, 10 Nov 2011 16:45:04 +0100 Subject: [PATCH] Lua: set a task metatable that allows OO-style syntax You can now write my_task:send(mailbox), which is just syntaxic sugar for simgrid.task.send(my_task, mailbox). --- src/bindings/lua/simgrid_lua.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/bindings/lua/simgrid_lua.c b/src/bindings/lua/simgrid_lua.c index b2f57d5109..205bfd4822 100644 --- a/src/bindings/lua/simgrid_lua.c +++ b/src/bindings/lua/simgrid_lua.c @@ -62,6 +62,11 @@ static m_task_t sglua_checktask(lua_State* L, int index) * - Argument 2 (number): computation size * - Argument 3 (number): communication size * - Return value (task): the task created + * + * A Lua task is a regular table with a full userdata inside, and both share + * the same metatable. For the regular table, the metatable allows OO-style + * writing such as your_task:send(someone). + * For the userdata, the metatable is used to check its type. */ static int l_task_new(lua_State* L) { @@ -76,6 +81,10 @@ static int l_task_new(lua_State* L) lua_newtable(L); /* task */ + luaL_getmetatable(L, TASK_MODULE_NAME); + /* task mt */ + lua_setmetatable(L, -2); + /* task */ m_task_t* lua_task = (m_task_t*) lua_newuserdata(L, sizeof(m_task_t)); /* task ctask */ *lua_task = msg_task; @@ -288,8 +297,11 @@ static int l_task_tostring(lua_State* L) return 1; } +/** + * \brief Metamethods of both a task table and the userdata inside it. + */ static const luaL_reg task_meta[] = { - {"__gc", l_task_gc}, + {"__gc", l_task_gc}, /* will be called only for userdata */ {"__tostring", l_task_tostring}, {NULL, NULL} }; @@ -849,12 +861,9 @@ static void register_task_functions(lua_State* L) lua_pushvalue(L, -2); /* simgrid.task mt simgrid.task */ /* metatable.__index = simgrid.task - * we put the task functions inside the task userdata itself: + * we put the task functions inside the task itself: * this allows to write task:method(args) for * simgrid.task.method(task, args) */ - // FIXME: in the current implementation, a Lua task is a table with a - // __simgrid_task field that contains the userdata, so the OO-style - // writing doesn't work lua_setfield(L, -2, "__index"); /* simgrid.task mt */ lua_pop(L, 2); -- 2.20.1