I need clarification on Metatable.__index - lua

I asked earlier why my methods for a metatable weren't being located by Lua, and was told that by setting __index to my metatable, that it would resolve the issue, so I assumed that a method when called was searching by index in the metatable, but I've ran into an issue now that I need to use indexing brackets [ and ] on my metatable, so __indexis assigned to return an index from a table inside of it, how do I resolve the functionality needs of both using methods, and use of indexing brackets
I wrote a minimal example indicating the problem:
TestMetatable = {DataTable = {}}
TestMetatable.__index = TestMetatable
function TestMetatable.new()
local Tmp = {}
setmetatable(Tmp,TestMetatable)
Tmp.DataTable = {1}
return Tmp
end
function TestMetatable:TestMethod()
print("Ran Successfully")
end
function TestMetatable.__index(self,index)
return self.DataTable[index]
end
local Test = TestMetatable.new()
-- both functionalities are needed
print(Test[1])
Test:TestMethod()

You need to understand the difference between __index and __newindex, and their relationship with the current contents of the main table.
__newindex is only called/accessed when all the following are true:
When you are setting a value into the main table, via tbl[index] = expr (or equivalent syntax, like tbl.name = expr).
When the key you are trying to set into the main table does not already exist in the main table.
The second one trips people up often. And that's your problem here, because __index is only accessed when:
When the key being read from the main table does not already exist in the main table.
So if you want to filter every read from and write to a table, then that table must always be empty. Therefore, those reads and writes need to go into some other table you create for each new object. So your new function needs to create two tables: one that remains empty and one that has all the data in it.
Honestly, I wish Lua had a way to create just an empty piece of userdata that you could bind a user-defined metatable to, just to avoid these issues.

the way I resolved this problem, according to Nicol Bolas's solution, if it might give clarity to anyone else's confusion :-)
TestMetatable = {DataTable = {}, FunctionTable = {}}
function TestMetatable.new()
local Tmp = {}
setmetatable(Tmp,TestMetatable)
Tmp.DataTable = {1}
Tmp.FunctionTable = TestMetatable
return Tmp
end
function TestMetatable:TestMethod()
print("Ran Successfully")
end
function TestMetatable.__index(self,index)
if type(index) == "string" then
return self.FunctionTable[index]
else
return self.DataTable[index]
end
end
local Test = TestMetatable.new()
-- both functionalities are needed
print(Test[1])
Test:TestMethod()

Related

Create local variables programmatically (in Lua)

Been having fun with a homebrew doco system in Lua. e.g.
fun("abs","return abs value", function (x,y)
return math.abs(x,y) end)
I'm stuck on one detail. I want to make "abs" a local function . But I do not know how to do that programmatically.
Of course, I could write to a field in some Lib object and call it Lib.abs(x,y) and I think that is what I'm going to have to do. BUT can any smart Lua person tell me how to not do that?
I don't think you have much of a choice, as while you can assign a value to a local variable (using debug.setlocal function), it's assigned by index, not by name, so there has to exist a local variable already with that index.
I don't see anything wrong with your suggestion to store the function in a table field.
What I would do is, I'd write(or even override) _G, run your function/program, and then restore it.
function callSandboxed(newGlobals, func)
local oldGlobals = {} --make a new table to store the values to be writen (to make sure we don't lose any values)
for i,_ in pairs(newGlobals) do
table.insert(oldGlobals, _G[i]) --Store the old values
_G[i] = newGlobals[i] --Write the new ones
end
func() --Call your function/program with the new globals
for i,v in pairs(oldGlobals) do
_G[i] = v --Restore everything
end
end
In this case, what you want to do is:
--Paste the callSandboxed function
callSandboxed({abs=math.abs},function()print(abs(-1))end) --Prints 1
If you want to remove ALL the old values from _G (not only the ones you want to replace), then you could use this:
function betterCallSandboxed(newGlobals, func) --There's no point deep copying now, we will replace the whole table
local oldGlobals = _G --Make a new table to store the values to be writen (to make sure we don't lose any values)
_G = newGlobals --Replace it with the new one
func() --Call your function/program with the new globals
_G = oldGlobals
end
Now if inside func, print and math(etc) are nil.

how is a function navigating through fields of a table

i already asked this question on stackoverflow and accepted an answer i think i did not really understand the answer and i got some more question, im embarrassed to necro it so im creating a new question
im learning lua and got to metatable part, in this example
local tb = {}
local meta = {}
function tb.new(s)
local super = {}
super.s = s
setmetatable(super,meta)
return super
end
function tb.add(s1,s2)
return s1.s..s2.s
end
meta.__add = tb.add
f= tb.new("W")
t= tb.new("E")
print(f+t)
when compiler gets tof = tb.new("W")
i think this happens
function tb.new("W") super.W = W return setmetatable(super,meta) return super end
so
print(f+t)
looks like
print(super+super)
how does
tb.add(super,super)
find the fields of super table using
return s1.s..s2.s
also as the
tb.new
function is called twice and
setmetatable(super,meta)
happens twice is there any difference between the first and second iteration? if any of the above are incorrect please correct me.
when compiler gets tof = tb.new("W") i think this happens function tb.new("W") super.W = W return setmetatable(super,meta) return super end
No. It's more like super['s'] = 'W'. That's how dot notation works. I hope that clarifies how Lua "finds the fields" later.
as the tb.new function is called twice and setmetatable(super,meta) happens twice is there any difference between the first and second iteration?
They're different, because the super variable is a new table each time. Any time you see {} (a table constructor), whether empty or not, it's creating an entirely new table. meta, however, is still the same table, because it only gets a table constructor once, outside of any function.

LUA - Create Meta Table with every sub table beeing a meta table again

but this will get confusing for sure.
I'm still very new to LUA and one thing i haven't worked much yet with is metatables.
I need to find a way to create a meta table which runs a function on editing values. This is not a problem if i stay on "one level", so the first index. Then i can simply use the __newindex to run it. But what i'm trying to do is to run the function whenever any value is changed.
This would require some way to set any table inside the metatable to be again a metatable running the same function as the "main" metatable
In my use case that would be a "save" function:
function MySaveFunction(tbl)
FileSave(my_settings_path, tbl)
end
MyTable = setmetatable()
MyTable.Value = value --> run MySaveFunction(MyTable.Value)
MyTable.SubTable = {} --> run setmetatable() on SubTable
MyTable.SubTable.Value = value --> run MySaveFunction(MyTable.SubTable.Value)
MyTable.SubTable.SubSubTable = {} --> run setmetatable() on SubSubTable
MyTable.SubTable.SubSubTable.Value = value --> run MySaveFunction(MyTable.SubTable.SubSubTable.Value)
MyTable.SubTable.SubSubSubTable = {} --> run setmetatable() on SubSubSubTable
MyTable.SubTable.SubSubSubTable.Value = value --> run MySaveFunction(MyTable.SubTable.SubSubSubTable.Value)
Hope someone can help me <.<
First thing to take a note of is that __newindex and __index metamethods are only triggered when they handle nil value in target table. If you want to track every single change, you can't just use __newindex, because once you write a value, subsequent calls won't do anything. Instead, you need to use a proxy table.
Another important thing to consider is tracking paths of accessed members.
Last, but not least, you need to remember to use raw access functions like e.g. rawget when implementing your handlers. Otherwise, you may encounter stack overflows or other weird behaviour.
Let's have a trivial example to illustrate the problems:
local mt = {}
function mt.__newindex (t, key, value)
if type(value) == "table" then
rawset(t, key, setmetatable(value, mt)) -- Set the metatable for nested table
-- Using `t[key] = setmetatable(value, mt)` here would cause an overflow.
else
print(t, key, "=", value) -- We expect to see output in stdout for each write
rawset(t, key, value)
end
end
local root = setmetatable({}, mt)
root.first = 1 -- table: 0xa40c30 first = 1
root.second = 2 -- table: 0xa40c30 second = 2
root.nested_table = {} -- /nothing/
root.nested_table.another = 4 -- table: 0xa403a0 another = 4
root.first = 5 -- /nothing/
Now, we need to deal with them. Let's start with a way to create a proxy table:
local
function make_proxy (data)
local proxy = {}
local metatable = {
__index = function (_, key) return rawget(data, key) end,
__newindex = function (_, key, value)
if type(value) == "table" then
rawset(data, key, make_proxy(value))
else
print(data, key, "=", value) -- Or your save function here!
rawset(data, key, value)
end
end
}
return setmetatable(proxy, metatable) -- setmetatable() simply returns `proxy`
end
This way you have three tables: proxy, metatable and data. User accesses proxy, but because it's completely empty on each access either __index or __newindex metamethods from metatable are called. Those handlers access data table to retrieve or set the actual values that user is interested in.
Run this in the same way as previously and you will get an improvement:
local root = make_proxy{}
root.first = 1 -- table: 0xa40c30 first = 1
root.second = 2 -- table: 0xa40c30 second = 2
root.nested_table = {} -- /nothing/
root.nested_table.another = 4 -- table: 0xa403a0 another = 4
root.first = 5 -- table: 0xa40c30 first = 5
This should give you an overview on why you should use a proxy table here and how to handle metamethods for it.
What's left is how to identify the path of the field that you are accessing. That part is covered in another answer to another question. I don't see a reason to duplicate it.

Lua table as frontend to database

I am attempting to implement a database as a Lua table. Using metatables, this table would be empty, and when an item is requested or modified in the table, it would return or modify the item in the database. The database itself would never be loaded into memory, except for the parts which are requested. It should be interacted with by the program as a table (as it is a table). The table, since it's only a "front", would save modified data to the database (rather than defining that item in the table).
In a table with no tables inside of it, this is easy to implement. I'm trying to make it work with a multi-layered table of indefinite depth.
(Aside: The database I'm considering is redis. Ideally this could be implemented for any database or database-like server by only changing the basic operating syntax.)
Because of the behavior of Lua's metatables, the __newindex method is only used when something is modified in the top-level (or created, if you're using a proxy). The __index method is called when something is read, even if the call is to modify something within a sub-table. Because of this, I'm trying to write an __index method that, when a table is requested, returns yet another pseudo-proxy (a table proxying a database rather than another tables) with the same behavior, except the proxy is for the table/array/list within the top-level, etc, to an indefinite depth. I am struggling.
My questions are:
Has this been implemented before?
Should I be focusing on "proper"
class system rather than what I'm doing now?
When you create a table, simply add an empty table in the fake and set it's metatable:
local fake = {}
do
local lookup = {} --Will be using this to avoid using lots of metatables
local real = {}
local meta
meta = {
__index = function(self,i)
return rawget(lookup[self], i)
end,
__newindex = function(self,i,v)
rawset(lookup[self], i, v)
if type(v) == "table" then
rawset(self, i, setmetatable({},meta))
lookup[self[i]] = v
end
end
}
setmetatable(fake, meta)
lookup[fake] = real
end
fake[1] = "hello"
print(fake[1])
print(rawget(fake, 1))
fake.x = {"hi"}
print(fake.x)
print(rawget(fake, 'x')) --This still prints a table because there actually is one, but in reality it's abiding by our rules
print(fake.x[1])
print(rawget(fake.x, 1))
fake.x.y = "aha"
print(fake.x.y)
print(rawget(fake.x, 'y'))
The only caveat with this method is they can directly modify the database like so:
fake.myvalue = {}
fake.myvalue = 5
Another method could be to wrap as you go:
local fake = {}
do
local lookup = {} --Will be using this to avoid using lots of metatables
local cache = {} --will be using to avoid usings tons of new objects
local real = {}
local meta
meta = {
__index = function(self,i)
local val = rawget(lookup[self], i)
if type(val) == "table" then
if cache[val] then
return cache[val]
else
local faker = {}
lookup[faker] = val
cache[val] = faker
return setmetatable(faker, meta)
end
else
return val
end
end,
__newindex = function(self,i,v)
rawset(lookup[self], i, v)
end
}
setmetatable(fake, meta)
lookup[fake] = real
end
fake[1] = "hello"
print(fake[1])
print(rawget(fake, 1))
fake.x = {"hi"}
print(fake.x)
print(rawget(fake, 'x')) --This still prints a table because there actually is one, but in reality it's abiding by our rules
print(fake.x[1])
print(rawget(fake.x, 1))
fake.x.y = "aha"
print(fake.x.y)
print(rawget(fake.x, 'y'))
Which avoids the direct modifying problem completely

Metamethod lookup through __index?

I've implemented my own class system and I'm having trouble with __tostring; I suspect a similar issue can happen with other metamethods, but I haven't tried.
(Brief detour: each class has a __classDict attribute, holding all methods. It is used as the class instances' __index. At the same time, the __classDict's __index is the superclass' __classDict, so methods in superclasses are authomatically looked up.)
I wanted to have a "default tostring" behavior in all instances. But it didn't work: the "tostring" behavior doesn't "propagate" through subclasses correctly.
I've done this test exemplifying my issue:
mt1 = {__tostring=function(x) return x.name or "no name" end }
mt2 = {}
setmetatable(mt2, {__index=mt1})
x = {name='x'}
y = {name='y'}
setmetatable(x, mt1)
setmetatable(y, mt2)
print(x) -- prints "x"
print(mt2.__tostring(y)) -- prints "y"
print(y) -- prints "table: 0x9e84c18" !!
I'd rather have that last line print "y".
Lua's "to_String" behaviour must be using the equivalent of
rawget(instance.class.__classDict, '__tostring')
instead of doing the equivalent of
instance.class.__classDict.__tostring
I suspect the same happens with all metamethods; rawget-equivalent operations are used.
I guess one thing I could do is copying all the metamethods when I do my subclassing (the equivalent on the above example would be doing mt2.__tostring = mt1.__tostring) but that is kind of inelegant.
Has anyone fought with this kind of issue? What where your solutions?
I suspect the same happens with all metamethods; rawget-equivalent operations are used.
That is correct.
from the lua manual:
... should be read as rawget(getmetatable(obj) or {}, event). That is, the access to a metamethod does not invoke other metamethods, and the access to objects with no metatables does not fail (it simply results in nil).
Generally each class has its own metatable, and you copy all references to functions into it.
That is, do mt2.__tostring = mt1.__tosting
Thanks to daurnimator's comments, I think I found a way to make metamethods "follow" __index as I want them to. It's condensed on this function:
local metamethods = {
'__add', '__sub', '__mul', '__div', '__mod', '__pow', '__unm', '__concat',
'__len', '__eq', '__lt', '__le', '__call', '__gc', '__tostring', '__newindex'
}
function setindirectmetatable(t, mt)
for _,m in ipairs(metamethods) do
rawset(mt, m, rawget(mt,m) or function(...)
local supermt = getmetatable(mt) or {}
local index = supermt.__index
if(type(index)=='function') then return index(t,m)(...) end
if(type(index)=='table') then return index[m](...) end
return nil
end)
end
return setmetatable(t, mt)
end
I hope it is straightforward enough. When a new metatable is set, it initializes it with all metamethods (without replacing existing ones). These metamethods are prepared to "pass on" requests to "parent metatables".
This is the simplest solution I could find. Well, I actually found a solution that used less characters and was a bit faster, but it involved black magic (it involved metatable functions de-referencing themselves inside their own bodies) and it was much less readable than this one.
If anyone finds a shorter, simpler function that does the same, I'll gladly give him the answer.
Usage is simple: replace setmetatable by setindirectmetatable when you want it to "go up":
mt1 = {__tostring=function(x) return x.name or "no name" end }
mt2 = {}
setmetatable(mt2, {__index=mt1})
x = {name='x'}
y = {name='y'}
setmetatable(x, mt1)
setindirectmetatable(y, mt2) -- only change in code
print(x) -- prints "x"
print(mt2.__tostring(y)) -- prints "y"
print(y) -- prints "y"
A little word of warning: setindirectmetatable creates metamethods on mt2. Changing that behavior so a copy is made, and mt2 remains unaltered, should be trivial. But letting them set up by default is actually better for my purposes.
From my experience with Lua 5.1, metamethods are looked up in metatables using rawget(), and that's why you must copy the reference to the function into every class table you create.
See the Inheritance Tutorial on the Lua Users Wiki.

Resources