Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some experiments with new Lua table functions.
require 'tablex'
local M = tonumber(arg[1]) or 10000
local N = tonumber(arg[2]) or 1000
local t_msg, t_start
function start_t (msg)
t_msg = msg
t_start = os.clock()
end
function end_t ()
print(('%s: %6.1f sec'):format(t_msg,os.clock() - t_start))
end
local new = function(N) return {} end
if arg[3] then
new = table.new
end
local function test_t_insert (N)
local t_insert = table.insert
local t = new(N)
for i = 1,N do
t_insert(t,i)
end
end
local function test_t_append2 (N)
local t_append = table.append
local t = new(N)
for i = 1,N,2 do
t_append(t,i,i+1)
end
end
local function test_t_plus (N)
local t = new(N)
for i = 1,N do
t[#t + 1] = i
end
end
local function append (t,v)
t[#t+1] = v
end
local function test_t_plusfun (N)
local t = new(N)
for i = 1,N do
append(t,v)
end
end
local function test_t_set (N)
local t = new(N)
for i = 1,N do
t[i] = i
end
end
start_t 'table.insert'
for i = 1,M do
test_t_insert(N)
end
end_t()
start_t 't[#t+1]=...'
for i = 1,M do
test_t_plus(N)
end
end_t()
start_t 't[#t+1] as fun'
for i = 1,M do
test_t_plusfun(N)
end
end_t()
start_t 't[i]=... loop i'
for i = 1,M do
test_t_set(N)
end
end_t()
start_t 'table.append 2'
for i = 1,M do
test_t_append2(N)
end
end_t()
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
static int l_tnew (lua_State *L) {
int narr = luaL_optint(L,1,0); // initial array slots, default 0
int nrec = luaL_optint(L,2,0); // intial hash slots, default 0
lua_createtable(L,narr,nrec);
return 1;
}
static int l_tappend (lua_State *L) {
int i,len = lua_objlen(L,1);
int N = lua_gettop(L);
for (i = 2; i <= N; i++) {
lua_pushvalue(L,i);
lua_rawseti(L,1,len+i-1);
}
return 0;
}
int luaopen_tablex(lua_State *L) {
lua_getglobal(L,"table");
lua_pushcfunction(L,l_tnew);
lua_setfield(L,-2,"new");
lua_pushcfunction(L,l_tappend);
lua_setfield(L,-2,"append");
return 0;
}
@craigbarnes

This comment has been minimized.

Copy link

commented Nov 27, 2013

Drive-by pedantry: the arguments to table.new() in LuaJIT 2.1 aren't optional :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.