关于 lua 表,类和函数有了解的吗?

我想知道为什么这个代码会输出 Mexico 而不是 England?我一直在尝试通过它们的属性,比如大陆,将 x1 到 x6 进行区分,但是没有取得太多进展。

world = {continent= "", country= ""}

function world:new (o,continent,country)
   o = o or {}
   setmetatable(o, self)
   self.__index = self
   self.continent= continent or ""
   self.country = country or "";
   return o
end

x1 = world:new(nil,"Europe","England")
x2 = world:new(nil,"Europe","France")
x3 = world:new(nil,"Africa","Algeria")
x4 = world:new(nil,"Africa","Nigera")
x5 = world:new(nil,"America","United States")
x6 = world:new(nil,"America","Mexico")

list_1 = {x1,x2,x3,x4,x5,x6}

print(list_1[1].country)
点赞
用户2117569
用户2117569

new 上下文中,self 是原始表格,o 是对象。在 self 上设置属性会覆盖先前的值。所以,将

self.continent= continent or ""
self.country = country or ""

更改为

o.continent= continent or ""
o.country = country or ""
2017-06-03 15:12:52