Last active
August 29, 2015 14:01
-
-
Save nadako/31eeac60b7406cfd4198 to your computer and use it in GitHub Desktop.
Haxe array & anon in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local Anon_mt = { | |
__newindex = function(self, key, value) | |
if value ~= nil then | |
rawset(self, key, value) | |
else | |
self._nils[key] = true | |
end | |
end, | |
__tostring = function(self) | |
local s = "{" | |
local keys = anon_keys(self) | |
local i = 0 | |
local len = #keys | |
while i < len do | |
local k = keys[i] | |
s = s .. k .. ":" .. tostring(self[k]) | |
i = i + 1 | |
if i ~= len then s = s .. ", " end | |
end | |
s = s .. "}" | |
return s | |
end | |
} | |
Anon = { | |
new = function() | |
return setmetatable({_nils = {}}, Anon_mt) | |
end | |
} | |
function anon_keys(s) | |
local a = Array:new() | |
for k, v in pairs(s) do | |
if k == "_nils" then | |
for k,v in pairs(v) do a:push(k) end | |
else | |
a:push(k) | |
end | |
end | |
return a | |
end | |
function anon_del(s, f) | |
s[f] = nil | |
s._nils[f] = nil | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local Array_mt = { | |
__index = { | |
push = function(self, item) self[self._len] = item end, | |
indexOf = function(self, item) | |
for i = 0, #self do | |
if self[i] == item then return i end | |
end | |
return -1 | |
end | |
}, | |
__newindex = function(self, key, item) | |
if key >= self._len then self._len = key + 1 end | |
rawset(self, key, item) | |
end, | |
__len = function(self) return self._len end, | |
__tostring = function(self) | |
local s = "[" | |
local i = 0 | |
local len = self._len | |
while i < len do | |
s = s .. tostring(self[i]) | |
i = i + 1 | |
if i ~= len then s = s .. ", " end | |
end | |
return s .. "]" | |
end | |
} | |
Array = { | |
new = function() | |
return setmetatable({_len = 0}, Array_mt) | |
end | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dofile "array.lua" | |
dofile "anon.lua" | |
local o = Anon:new() | |
o["hello"] = 1 | |
o["bye"] = nil | |
print(o) -- {bye:nil, hello:1} | |
anon_del(o, "bye") | |
print(o) -- {hello:1} | |
local a = Array:new() | |
a:push(10) | |
a:push(20) | |
a:push(nil) | |
a:push(30) | |
a:push(nil) | |
print(a, #a) -- [10, 20, nil, 30, nil] 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment