Xuer
Xuer

Reputation: 83

I dont understand the syntax here

i came across a post about metatable on roblox devforum,in proxy table part i dont understand the syntax of this code

local function TrackDownTable()
  local t = {x = 5}
  local proxy = setmetatable({}, {
  __index = function(_, key)
      print("User indexed table with "..key)
      return t[key]
  end,
  __newindex = function(_, key, value)
   print("User made or update the field "..key.." with the value "..value.." in table")
   t[key] = value
  end
  })
  return proxy

end

local t = TrackDownTable()
t.x = 5 
print(t.x) 

in this part

local t = TrackDownTable()
t.x = 5 

what does local t = TrackdownTable() do? and how does this part t.x = 5 acces proxy table?

Upvotes: 1

Views: 139

Answers (1)

Piglet
Piglet

Reputation: 28994

This is a very simple proxy demo table.

A proxy table is a table that controls table access. You can use it to track table access or to implement a read only table for example.

There is no way for you to access or modify that table's data without going through the proxy table.

It is actually quite simple. TrackDownTable creates t, which is just some demo table. We just need a simple table to demonstrate table access. So we create a minimum table with a single field {x=5}

local proxy = setmetatable({}, {
  __index = function(_, key)
      print("User indexed table with "..key)
      return t[key]
  end,
  __newindex = function(_, key, value)
   print("User made or update the field "..key.." with the value "..value.." in table")
   t[key] = value
  end
  })

can be rewritten as:

local metatable = {}
metatable.__index =  function(_, key)
      print("User indexed table with "..key)
      return t[key]
  end

metatable.__newindex = function(_, key, value)
   print("User made or update the field "..key.." with the value "..value.." in table")
   t[key] = value
  end

local proxy = {}

setmetatable(proxy, metatable)

This code simply creates a metatable with an __index and a __newindex metamethod and sets it as the metatable of our demo table.

__index is invoked when you index a field of proxy.

__newindex is invoked when you assign a value to an index in proxy.

Edit:

want to know is how is this assignmentt.x = 5 passed to the proxy table as ``local t = TrackDownTable() ``` when t.x = 5 happens what does it do, it passes 5 as the parameter to the function?

t.x = 5 is an indexing assignment. If you execute this Lua will check if there is a field with key "x" in t. As t["x"] is nil in this scope it will check if there is a metatable. There is, so it will call our __newindex metamethod which has 3 parameters (table, key, value)

So we actually call getmetatable(t).__index(t, "x", 5) which internally will assign the value to the local t.x defined inside TrackDownTable.

It is a bit misleading that both tables are named t in this example.

Please read https://www.lua.org/manual/5.4/manual.html#2.4

Upvotes: 2

Related Questions