Is this a bug in lua or a function unknown to me?

I try to teach my friend how lua, basically, and he comes to me with this code, and he drinks my head:

a = {name = "aaa"}

function a:new()
  self.x = "sss"
  o = {}
  setmetatable(o, self)
  self.__index = self
  return o
end

function a:some()
  return "[ " .. self.name .. " ]"
end

b = a:new()
print(b:some())
print(b.x)

which prints

[ aaa ] sss

both should not be possible since they were never installed on the oinsidea:new

after some debugging, I look into it, and here some interesting things happen:

a = {name = "aaa", x = "sss"}

function a:new()
  o = {}
  print(o.x, self.x)
   -- nil sss
  setmetatable(o, self)
  print(o.x, self.x, o, self, self.__index, o.__index)
   -- nil sss table: 0x1001280 table: 0x1001320 table: 0x1001320 nil
  self.__index = self
  print(o.x, self.x, o, self, self.__index, o.__index)
   -- sss sss table: 0x1001280 table: 0x1001320 table: 0x1001320 table: 0x1001320
  return o
end

Note that on the third printit returns a value .x self, but it was called from o, which has no "relationship" with "I", how is this possible?

+4
source share
1 answer

a __index , a:new(). - b, a. x name b, .

+1

Source: https://habr.com/ru/post/1688641/


All Articles