2015-05-08 101 views
0

以下問題是我:功能參數LUA

我想有一個在Lua創建一個新對象的功能,但它應該是可以延長它。

function Class(table) 
local a = {} 
local t = {create = _create, __newindex = function(o,k,v) 
      if k == "create" then 
       --getmetatable(o).create = function() 
       --_create(o) 
       --v() 
       --end 
       -- or just create(v.params) 
      else 
       rawset(o,k,v) 
      end 
      end, 
} 

setmetatable(a,t) 
t.__index = t 
end 

function _create(o,...) 
return newTable 
end 

ele = Class:create() 
function Class:create(n) 
    self.name = n 
end 
ele2 = Class:create("bbbb") 

現在ele2是沒有名字的,但它schould是創建一個新的對象與給定的字符串作爲名稱。

我可以從newindex獲得給定值(類型函數)的參數還是我可以執行該值?

+2

什麼是'了'?什麼是'newTable'?你有沒有給函數metatables? (當'Class'是一個函數時,'Class:create'如何工作?) –

+0

看看我的迴應:http://stackoverflow.com/questions/30128069/unable-to-figure-out-lua-table -inheritence – tonypdmtr

回答

0

有幾件事我不確定。 Etan說,什麼是newTable,爲什麼你要設置create作爲Class的函數,當Class是一個函數?

如果你正在尋找一種方式被創建時初始化一個類的實例,你可以做這樣的事情:

function Class() 
    local class = {} 
    class.__index = class 
    return setmetatable(class, {__call = function(...) 
     local instance = setmetatable({}, class) 
     if instance.init then 
      instance:init(select(2, ...)) 
     end 
     return instance 
    end}) 
end 

--now an example: 

Dog = Class() 

function Dog:init(name) 
    self.name = name 
end 

function Dog:bark() 
    print(string.format("%s barked!", self.name)) 
end 

local pedro = Dog("Pedro") 
pedro:bark() --> pedro barked!