// Copyright (C) 2012-2013 ChaosForge / Kornel Kisielewicz // http://chaosforge.org/ // // This file is part of NV Libraries. // For conditions of distribution and use, see copyright notice in nv.hh #include "nv/lua/lua_aux.hh" static int nlua_table_copy( lua_State* L ) { luaL_checktype( L, 1, LUA_TTABLE ); lua_settop( L, 1 ); lua_newtable(L); lua_pushnil(L); while ( lua_next( L, 1 ) != 0 ) { lua_pushvalue(L, -2); lua_insert(L, -2); lua_settable(L, -4); } return 1; } static int nlua_table_icopy( lua_State* L ) { luaL_checktype( L, 1, LUA_TTABLE ); lua_settop( L, 1 ); lua_newtable(L); int i = 0; for(;;) { i++; lua_rawgeti(L, 1, i); if ( lua_isnil( L, -1 ) ) { lua_pop( L, 1 ); break; } lua_rawseti(L, 2, i); }; return 1; } static int nlua_table_merge( lua_State* L ) { luaL_checktype( L, 1, LUA_TTABLE ); luaL_checktype( L, 2, LUA_TTABLE ); lua_settop( L, 2 ); lua_pushnil(L); while ( lua_next( L, 2 ) != 0 ) { lua_pushvalue(L, -2); lua_insert(L, -2); lua_settable(L, 1); } return 0; } static int nlua_table_imerge( lua_State* L ) { luaL_checktype( L, 1, LUA_TTABLE ); luaL_checktype( L, 2, LUA_TTABLE ); lua_settop( L, 2 ); int i = 0; for(;;) { i++; lua_rawgeti(L, 2, i); if ( lua_isnil( L, -1 ) ) { lua_pop( L, 1 ); break; } lua_rawseti(L, 1, i); }; return 0; } static int nlua_table_reversed( lua_State* L ) { luaL_checktype( L, 1, LUA_TTABLE ); lua_settop( L, 1 ); int len = lua_rawlen(L,1); int i = len; lua_createtable(L,len,0); while ( i != 0 ) { lua_rawgeti(L, 1, i); lua_rawseti(L, 2, len-i+1); i--; } return 1; } static int nlua_table_toset( lua_State* L ) { luaL_checktype( L, 1, LUA_TTABLE ); lua_settop( L, 1 ); lua_newtable(L); int i = 0; for(;;) { i++; lua_rawgeti(L, 1, i); if ( lua_isnil( L, -1 ) ) { lua_pop( L, 1 ); break; } lua_pushboolean( L, true ); lua_rawset(L, 2); }; return 1; } static const struct luaL_Reg nlua_table_aux_f [] = { { "copy", nlua_table_copy }, { "icopy", nlua_table_icopy }, { "merge", nlua_table_merge }, { "imerge", nlua_table_imerge }, { "reversed", nlua_table_reversed }, { "toset", nlua_table_toset }, { NULL, NULL } }; static const struct luaL_Reg nlua_math_aux_f [] = { { NULL, NULL } }; void nlua_register_aux( lua_State* L ) { lua_getglobal( L, "table" ); luaL_setfuncs( L, nlua_table_aux_f, 0 ); lua_pop( L, 1 ); lua_getglobal( L, "math" ); luaL_setfuncs( L, nlua_math_aux_f, 0 ); lua_pop( L, 1 ); }