[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: [ANN] luamem: struct, array, call DLL
- From: Nodir Temirhodzhaev <nvtem@...>
- Date: Fri, 15 Oct 2004 01:15:56 -0700 (PDT)
Take at
http://lua-users.org/files/wiki_insecure/users/tnodir/
-- Examples:
-- :: Plain array ::
local arr = assert(mem.alloc(8)) -- Default type is
byte
for i = 0, 7 do arr[i] = 65 + i end
for i = 0, 7 do print(string.char(arr[i])) end
arr[0] = "zstring\0"
print(mem.tostring(arr))
mem.free(arr)
-- :: Nested structure ::
local rgb2point_t = mem.struct{
mem.int, "x", "y";
mem.struct{mem.byte, "r", "g", "b"}, "rgb";
}
local ptr = assert(mem.alloc(2 *
mem.sizeof(rgb2point_t)))
mem.def(ptr, rgb2point_t)
-- Don't use following (for nested keys (index|field)
more then 1),
-- because Lua optimize access to fields.
-- ptr.rgb.r, ptr.rgb.g, ptr.rgb.b = 22, 33, 44
ptr.rgb.r = 22; ptr.rgb.g = 33; ptr.rgb.b = 44
print(ptr.rgb.r, ptr.rgb.g, ptr.rgb.b)
-- But this is correct assignment
ptr.x, ptr.y = 100, 200
print(ptr.x, ptr.y)
-- Array
ptr[1].x = 300; ptr[1].y = 400
print(ptr[1].x, ptr[1].y)
-- Copy struct
local rgb1 = mem.base(ptr[1].rgb)
rgb1[0] = ptr[nil].rgb -- Equal to
-- mem.copy(rgb1, ptr[nil].rgb, mem.sizeof(rgb1))
-- [nil] is used to reset nesting remained from
ptr[1].rgb.
print(rgb1.r, rgb1.g, rgb1.b)
-- Access to field by number
ptr.y = 4768;
if ptr.y ~= ptr'f'[2] then
error"Field by number"
end
-- Set multiple values
ptr[0] = {100, 200, {11, 22, 33}}
print(ptr[0].rgb.g)
mem.free(ptr)
-- :: Memory alignment ::
if mem.sizeof(mem.struct{mem.byte, "b"; 1, mem.int,
"i"})
~= mem.sizeof(mem.struct{mem.int, 2, "i"}) then
error"Memory alignment"
end
-- :: Call DLL function ::
local beep = mem.new(mem.cfunction)
beep[0] = assert(loadlib("kernel32.dll", "Beep"))
local param = mem.new(mem.struct{mem.int, "freq",
"duration"})
param[0] = {3300, 440}
print(beep(param))
beep, param = nil, nil
-- :: Benchmark: array vs. table ::
local N = 13000
-- Array
local time = os.clock()
local rgb_t = mem.struct{mem.byte, "r", "g", "b"}
local arr = assert(mem.alloc(N * mem.sizeof(rgb_t)))
mem.def(arr, rgb_t)
local p = mem.base(arr)
for i = 0, N-1 do
p.r, p.g, p.b = 1, 2, 3
p = p + 1
end
mem.free(arr)
print("Array=", os.clock()-time)
-- Table
time = os.clock()
local tbl, p = {}
for i = 1, N do
p = {r = 1, g = 2, b = 3}
tbl[i] = p
end
print("Table=", os.clock()-time)
--[[
On my P4 2,41GHz 256Mb WinXP:
N < 13000: Equal.
Array Table
N ~ 13000: 0.031 0.046
N = 90000: 0.171 0.25
N = 900000: 1.66 3.5
]]
__________________________________
Do you Yahoo!?
Yahoo! Mail Address AutoComplete - You start. We finish.
http://promotions.yahoo.com/new_mail