provides an easy way to copy a table from Lua (simple assignment only makes an alias, but sometimes an independent table is desired) currently this function only performs a shallow copy, but I think it should be changed to do a deep copy (possibly of configurable depth?) that maintains the internal table reference structure
| 1918 | // but I think it should be changed to do a deep copy (possibly of configurable depth?) |
| 1919 | // that maintains the internal table reference structure |
| 1920 | static int copytable(lua_State *L) |
| 1921 | { |
| 1922 | int origIndex = 1; // we only care about the first argument |
| 1923 | int origType = lua_type(L, origIndex); |
| 1924 | if(origType == LUA_TNIL) |
| 1925 | { |
| 1926 | lua_pushnil(L); |
| 1927 | return 1; |
| 1928 | } |
| 1929 | if(origType != LUA_TTABLE) |
| 1930 | { |
| 1931 | luaL_typerror(L, 1, lua_typename(L, LUA_TTABLE)); |
| 1932 | lua_pushnil(L); |
| 1933 | return 1; |
| 1934 | } |
| 1935 | |
| 1936 | lua_createtable(L, lua_objlen(L,1), 0); |
| 1937 | int copyIndex = lua_gettop(L); |
| 1938 | |
| 1939 | lua_pushnil(L); // first key |
| 1940 | int keyIndex = lua_gettop(L); |
| 1941 | int valueIndex = keyIndex + 1; |
| 1942 | |
| 1943 | while(lua_next(L, origIndex)) |
| 1944 | { |
| 1945 | lua_pushvalue(L, keyIndex); |
| 1946 | lua_pushvalue(L, valueIndex); |
| 1947 | lua_rawset(L, copyIndex); // copytable[key] = value |
| 1948 | lua_pop(L, 1); |
| 1949 | } |
| 1950 | |
| 1951 | // copy the reference to the metatable as well, if any |
| 1952 | if(lua_getmetatable(L, origIndex)) |
| 1953 | lua_setmetatable(L, copyIndex); |
| 1954 | |
| 1955 | return 1; // return the new table |
| 1956 | } |
| 1957 | |
| 1958 | // because print traditionally shows the address of tables, |
| 1959 | // and the print function I provide instead shows the contents of tables, |
nothing calls this directly
no test coverage detected