F
F
Fuduin2014-07-19 05:29:31
Lua
Fuduin, 2014-07-19 05:29:31

[Lua] Why is a table inside a metatable considered "static"?

Object.lua file

local base = _G

module("Object")

local CObject = {
  position = {
    x = 0,
    y = 0
  },
  text = "Some text"
}

function new()
  local res = {}
  base.setmetatable(res, { __index = CObject })

  return res
end

main.lua file
require("Object")

local object1, object2

object1 = Object.new()
object2 = Object.new()

object1.text = "qwerty"
object2.text = "asdfg"

print(object1.text) -- выведет qwerty
print(object2.text) -- выведет asdfg

object1.position.x = 1
object2.position.x = 2

print(object1.position.x) -- выведет 2
print(object2.position.x) -- выведет 2

Question: why if there is a table inside the metatable, then it behaves like a "static field", while other elements do not? What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fuduin, 2014-07-19
@Fuduin

Most likely this is due to the fact that all work with tables occurs by reference. Therefore, when there is a call to position (for any table with a CObject metatable), we get a link to the position table that was created in the CObject table.
So far, I came up with the following as a solution, declare the table in the metatable as nil and create a function that will redefine position as a table and enter all the values ​​there.
If there are more adequate solutions, write, I will be glad. Below is the code of the Object.lua file

local base = _G

module("Object")

local CObject = {
  position = nil,
  text = "Some text"
}

function CObject:init()
  self.position = {}
  self.position.x = 0
  self.position.y = 0
end

function new()
  local res = {}
  base.setmetatable(res, { __index = CObject })
  res:init()

  return res
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question