lua-users home
lua-l archive

Re: A proposal for the confusing pseudo table ≈ array concept

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2018年01月19日 19:46 GMT+02:00 Dirk Laurie <dirk.laurie@gmail.com>:
> I append the module 'list' and the module 'dclass' on which it depends.
-- dclass.lua © Dirk Laurie 2018 MIT License like Lua's.
--[=[ Very simple support for classes. 
 MyClass = class("my class",_methods) 
-- Name of class must be given. If `_methods` is not nil, it must be 
-- a table, whose contents will be copied into 'MyClass'.
 MyClass.method = function(object,...) --[[function body]] end
 obj = MyClass(...)
-- If `MyClass.init` is `false`, `...` is ignored.
-- If `MyClass.init` is a function, `obj:init(...)` is called by MyClass. 
-- Otherwise, the first argument in `...` must be nil or a table, 
-- whose contents will be copied into `obj`. 
--]=]
local class -- semi-global forward declaration
 do 
local new -- forward declaration
class = function(name,_methods) -- class creator
 if type(name)~='string' then error(
 "Bad argument #1 to 'class' (expected string, got "..type(name)..")")
 end
 if type(_methods)~='table' and type(_methods)~='nil' then error(
 "Bad argument #2 to 'class' (expected table, got "..type(_methods)..")")
 end
 local methods = {init="No initializer for class '"..name..
 "' has been defined yet."}
 if _methods then
 for k,v in pairs(_methods) do methods[k]=v end
 end
 methods.__name = name
 methods.__index = methods
 local meta = {__call=new,__name="constructor-metatable for class '"..name.."'"}
 local Class = setmetatable(methods,meta)
 return Class
end
new = function(Class,...) -- generic constructor
 object = setmetatable({},Class)
 if type(Class.init)=='function' then 
 object:init(...) 
 elseif Class.init~=false then
 if type(...)=='table' then
 for k,v in pairs((...)) do object[k]=v end
 elseif type(...) ~= 'nil' then error("Bad initializer to class '"..
 Class.__name.."' (expected table, got "..type(...)..")")
 end
 end
 return object
end
 end 
 return class -- comment out this line if dclass.lua is copied into code
-- end of file dclass.lua
-- list.lua © Dirk Laurie 2018 MIT License like Lua's.
local class = require "dclass"
local list = class("list",table)
local none = '⎕'
function list:__len() return self._len end
function list:init(...)
 local t = table.pack(...)
 self._len = t.n
 for k=1,t.n do
 local v = t[k]
 if v==nil then v = none end
 self[k] = v
 end
end
return list

AltStyle によって変換されたページ (->オリジナル) /