Skip to content

Instantly share code, notes, and snippets.

@deepak1556
Created May 12, 2013 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepak1556/5563649 to your computer and use it in GitHub Desktop.
Save deepak1556/5563649 to your computer and use it in GitHub Desktop.
simple javascript methods such as pop(),splice(),indexOf(),instanceof(),extend(),apply() in lua
function pop (arr)
local d = arr[table.getn(arr)]
table.remove(arr)
return d
end
function instanceof (obj1,obj2)
obj2 = tostring (obj2)
local mt = getmetatable (obj1)
while true do
if mt == nil then return false end
if tostring (mt) == super then return true end
mt = getmetatable (mt)
end
end
function indexOf (arr, elem)
local result
if "table" == type(arr) then
for i=1,#arr do
if elem = arr[i] then
result = i
break
end
end
end
return result
end
function splice (arr, index, howmany)
local new_arr = {}
local table_size = table.getn(arr)
if index < 1 then
index = 1
end
if howmany < 0 then
howmany = 0
end
if index > table_size then
index = table_size + 1
howmany = 0
end
if index + howmany > table_size then
howmany = table_size - index + 1
end
for i=1,index do
table.insert(new_arr,arr[i])
end
for i=index + howmany - 1,table_size do
table.insert(new_arr,arr[i])
end
return new_arr
end
function extend (parent, obj1, obj2)
if type(obj2) ~= "table" then
return
end
for i,v in pairs(obj2) do
table.insert(obj1,i,v)
end
if type(parent) ~= "table" then
return obj1 or parent
end
temp_obj = obj1 or {}
temp_obj.__index = parent
return setmetatable(parent, temp_obj)
end
function apply (cb, self, obj)
if type(cb) == "function" then
cb = Object:extend()
setmetatable(cb:new(),{__index = self})
cb(obj)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment