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?
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
Related
I have this table in lua:
local values={"a", "b", "c"}
is there a way to return the index of the table if a variable equals one the table entries?
say
local onevalue = "a"
how can I get the index of "a" or onevalue in the table without iterating all values?
There is no way to do that without iterating.
If you find yourself needing to do this frequently, consider building an inverse index:
local index={}
for k,v in pairs(values) do
index[v]=k
end
return index["a"]
The accepted answer works, but there is room for improvement:
Why not exit the loop once the element is found? And why bother copying the entire source table into a new throwaway table?
Usually, this sort of function returns the first array index with that value, not an arbitrary array index with that value.
For arrays:
-- Return the first index with the given value (or nil if not found).
function indexOf(array, value)
for i, v in ipairs(array) do
if v == value then
return i
end
end
return nil
end
print(indexOf({'b', 'a', 'a'}, 'a')) -- 2
For hash tables:
-- Return a key with the given value (or nil if not found). If there are
-- multiple keys with that value, the particular key returned is arbitrary.
function keyOf(tbl, value)
for k, v in pairs(tbl) do
if v == value then
return k
end
end
return nil
end
print(keyOf({ a = 1, b = 2 }, 2)) -- 'b'
If you use Lua for Roblox development, you can use the table.find method:
print(table.find({'a', 'b', 'c'}, 'b'))
Consider the following code:
#!/usr/bin/lua
local field =
{
name = '',
array = {},
new = function(self, o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end,
}
local fld1 = field:new()
local fld2 = field:new()
fld1.name = 'hello'
table.insert(fld1.array, 1)
table.insert(fld1.array, 2)
table.insert(fld1.array, 3)
fld2.name = 'me'
table.insert(fld2.array, 4)
table.insert(fld2.array, 5)
print('fld1: name='..fld1.name..' len='..#fld1.array)
print('fld2: name='..fld2.name..' len='..#fld2.array)
The output when executed is as follows:
fld1: name=hello len=5
fld2: name=me len=5
From the output, it can be seen that name has different values in fld1 and fld2. array, however, has the same value in fld1 and fld2 (fld1.array and fld2.array are the same and therefore have the same length of 5).
How do I fix this code so that fld1.array is independent of fld2.array (so that modifying fld1.array does not change fld2.array)?
First off, fld1 and fld2 have distinct names because you gave them distinct names - their own properties.
When you perform table key assignment the new key and value are stored directly in the table that you specify. The __index metamethod only comes in to play when you perform table key lookup and the key is not found in the table.
A quick example where we can see that table key assignment will shadow keys in the __index lookup chain.
local Foo = { shared = 'shared', private = 'private' }
Foo.__index = Foo
local foo = setmetatable({}, Foo)
foo.private = 'a shadowed value'
print(Foo.shared, foo.shared) -- shared shared
print(Foo.private, foo.private) -- private a shadowed value
Note: there is a __newindex metamethod for catching table key assignment that involves a never-before-seen key.
Consider treating the new method more like a traditional constructor function, wherein you assign 'private' properties to newly created instances.
local Field = {
-- shared properties go here
}
-- shared methods are defined as such
function Field:new (name)
local o = {
-- private properties for the newly created object go here
name = name or '',
array = {}
}
self.__index = self
return setmetatable(o, self)
end
function Field:insert (value)
table.insert(self.array, value)
end
local fld1 = Field:new('hello')
local fld2 = Field:new('me')
fld1:insert(1)
fld1:insert(2)
fld1:insert(3)
fld2:insert(4)
fld2:insert(5)
print('fld1: name='..fld1.name..' len='..#fld1.array) -- fld1: name=hello len=3
print('fld2: name='..fld2.name..' len='..#fld2.array) -- fld2: name=me len=2
Some more notes:
Generally, 'class' names should be in PascalCase, to make them distinct.
Having a :new function in the lookup chain means instances can invoke it, this may or may not be desirable. (Can create slightly ugly inheritance this way.)
There is a difference between how you define methods which use the implicit self. You should give Chapter 16 of Programming in Lua a read. It might be a tad dated if you're using 5.2 or 5.3, but it should still have a lots of useful information.
If you're interested in a tiny library for this, I recently wrote Base. If you look around, you'll find lots of little OOP packages for making these kinds of things a bit easier.
Lua's oop technic not same c++, java
__index metamethod reference target table record.
and so, fld1, fld2 array item is Field's array item.
you must make a new table and use it.
why name's value different. Because, Your assign a name
fld1.name = 'hello'
simply code fix
fld1.array = {}
using new method code fix
local o1 = {name = '', array = {}}
local o2 = {name = '', array = {}}
local fld1 = field:new(o1)
local fld2 = field:new(o2)
make new table(make o) and insert new method.
I'm trying to get table key name from a value.
tostring only returns table: XXXXXXXXX
I tried some functions but nothing work.
config = {
opt1 = "etc..."
}
players = {}
function openMenu(playerName, configTable)
players[playerName] = Something to get Table Key...
-- read the table and create a gui not yet made
end
And next, if I do this :
print(players[playerName])
I want to get this output :
"config"
You will need to iterate over all pairs of the table and return the key if the value is equal. Note that this will only return one binding, even if multiple keys can lead to the same value:
function find(tbl, val)
for k, v in pairs(tbl) do
if v == val then return k end
end
return nil
end
table.find(t, value [,start_index]) -> [key or nil]
I have an empty table which I want to act as a "gateway" to another set of functions at another location.
tbl = {}
I want to pass called functions from this table to somewhere else as a string:
tbl.someMethod("hello")
I've tried this with limited success.
hand = {
__index = function(tbl, name)
hand[name] = function(...)
passToSomewhere(name, ...)
end
end,
__call = function(tbl, name, ...)
hand[name](...)
end
}
setmetatable(tbl, hand)
tbl.someFunction("hello!", someTbl, someNumber)
How do I forward the undefined function through the table without it throwing errors?
Edit: More detail
I'm trying to define and call a function in a table in one call:
tbl = {}
hand = {
__index = function(tbl, name)
print(name)
tbl[name] = function(...)
print(...)
end
end
}
setmetatable(tbl, hand)
s,e = pcall(tbl.help,"banana","goat")
print(s)
s,e = pcall(tbl.help,"banana","goat")
print(s)
This code does work but the first pcall will throw an error because the function hasn't been defined yet.
Say I wanted to use an library which I know updates quite a lot and keep my script compatible and this library may not be present on my computer. I would like to forward calls to this library across some interface but I still want to be able to call the functions in the same way.
--For example I would like to call this function like this:
someLib.doSomething(name, age, telephone)
--Instead of passing it through another function:
someOtherLib.invoke("someLib.doSomething", name, age, telephone)
Is this possible?
Edit 2:
Thanks #greatwolf !
This is my working test code.
tbl = {}
hand = {
__index = function(tbl, name)
tbl[name] = function(...)
return print(name, ...)
end
return rawget(tbl, name)
end
}
setmetatable(tbl, hand)
tbl.help("banana","goat")
Okay, based on your updated details you want lua to translate this call
someLib.doSomething(name, age, telephone)
into
someOtherLib.invoke("someLib.doSomething", name, age, telephone)
behind the scenes. What you have is almost there, you just need to return the newly created function back:
__index = function(tbl, name)
tbl[name] = function(...)
return someOtherLib.invoke("someLib."..name, ...)
end
-- return tbl[name] works too, I used rawget to indicate
-- no further __index lookup should be done
return rawget(tbl, name)
end
Now, if your someOtherLib is just a table of functions, lhf's suggestion will work too
setmetatable(tbl, {__index = someOtherLib})
Now if your someOtherLib provides someway to get the function you want to call without actually invoking it just yet, __index can relay this without creating extra closure wrappers
__index = function(tbl, name)
tbl[name] = someOtherLib.getFuncByName(name)
return tbl[name]
end
The __call metamethod is not needed here.
In Lua how would one pop/remove the next item (any order) in a key-value-pair table?
Is this possible without having to iterate using pairs?
There is a primitive function next, you can call next(t,k), where k is a key of the table t, returns a next key in the table, in an arbitrary order, and the value associated with this key.
If k is nil, next(t,k) returns the first element if there is one. So you can iterate the table from calling next(t,nil) and end when the next key is nil.
This is an simple example to demonstrate the use of next:
local t = {a = "va", b = "vb", c = "vc"}
local k,v = next(t,nil)
print(k,v)
k,v = next(t,k)
print(k,v)
k,v = next(t,k)
print(k,v)
k,v = next(t,k)
print(k,v)
Output:
a va
c vc
b vb
nil nil
The global function next is useful here. The docs explain it pretty well in general. To use it iteratively, this is 'key':
You may ... modify existing fields. In particular, you may clear
existing fields.
A simple pop function:
-- removes and returns an arbitrary key-value pair from a table, otherwise nil
local pop = function (t)
local key, value = next(t)
if key ~= nil then
t[key] = nil
end
return key, value
end
Demo:
local test = { "one", c = "see", "two", a = "ayy", b = "bee", "three" }
assert(next(test), "Table was expected to be non-empty")
local key, value = pop(test)
while key do
print(key, value)
key, value = pop(test)
end
assert(not next(test), "Table was expected to be empty")
If you run the demo multiple times, you might see the arbitrariness of the table sequence.