Lua metatable, how to forward undefined functions? - lua

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.

Related

Converting a line of code to a char string

I recently wrote some code like this:
function enum(tbl)
local length = #tbl
for i = 1, length do
local v = tbl[i]
tbl[v] = i
end
return tbl
end
eItemType = enum
{
"wpn",
"outf",
"helm",
"art",
"boost",
"bkpk",
"dev",
"ammo",
"none"
}
It works. But I would like to simplify it to this form:
enum eItemType
{
"wpn",
"outf",
"helm",
"art",
"boost",
"bkpk",
"dev",
"ammo",
"none"
}
For the enum function to create a global variable eItemType in the file from which it is called.
I don't know how to implement this (convert eItemType to string in string code).
Functions from the debug library come to mind, namely getline, maybe it can handle it...
Enumerations in Lua
First of all: You're shoehorning a foreign language concept into Lua, which will necessarily not be round on the corners. Languages like C use numbers (integers) for enums because of their efficiency: Integer comparison is fast. In the end, enums are just synctactic sugar for enumerating integer constants though. You don't need any of this in Lua: Lua has string interning, which means strings are only stored once in memory and can be compared as fast as numbers. That is, the naive way to implement enums in Lua, is to simply use strings right away!
local enum_values = {"foo", "bar", "baz"}
local function get_random_enum_value()
return enum_values[math.random(#enum_values)]
end
if get_random_enum_value() == "foo" then
print("Congratulations! The value is foo!")
end
The downside is that you now don't have any table holding your enum values, so you'll either want to brush up on your documentation or create a (redundant) hash table to hold your enum values (which really is just making things slower, but may help readability). You don't need to involve any numbers. If I inspect a table and see a "foo_something" string there, that's a lot more useful than 42.
local my_enum = {foo = "foo", bar = "bar", baz = "baz"}
local enum_values = {my_enum.foo, my_enum.bar, my_enum.baz}
local function get_random_enum_value()
return enum_values[math.random(#enum_values)]
end
-- May be considered more readable since we now have a scope for "foo"
if get_random_enum_value() == my_enum.foo then
print("Congratulations! The value is foo!")
end
then you'd probably write yourself a simple helper to generate these kinds of tables:
function enum(namelist)
local t = {}
for _, v in pairs(namelist) do
t[v] = v
end
return t
end
my_enum = enum{
"foo",
"bar",
"baz",
}
Syntactic Sugar
What you want is called syntactic sugar and yes, it requires Lua's metaprogramming capabilities. If you really want an enum keyword, you'll have to extend Lua or implement a preprocessor adding such a keyword.
First, let's see how Lua sees your current code:
someName = enum { ... }
parses as "call the variable called enum with the table { ... } and assign the result to the variable called someName".
enum someName { ... }
does not parse: this is just a name, followed by... another name? Syntax error. By slightly abridging this syntax, it is however still possible to turn this into a valid expression. How about passing someName as a string to enum, which then returns a function to apply to your table?
enum "someName" { ... }
this would be implemented as
function enum(name)
return function(t)
_G[name] = original_enum(t)
end
end
where original_enum is your original enum function without the added layer for syntactic sugar. You might want to swap out _G with _ENV or getfenv(2) or similar.
Or for another syntactic sugar, you could also use the indexing operator paired with the __index metamethod:
enum.someName { ... }
which is implemented as:
enum = setmetatable({} --[[proxy table]], {__index = function(_, name)
return function(t)
_G[name] = original_enum(t)
end
})
both of these have in common that they are basically just fancy ways of currying the name of the global variable you want to assign to.
f you need to get a table from a string, then try:
local s = [[ return {
"wpn",
"outf",
"helm",
"art",
"boost",
"bkpk",
"dev",
"ammo",
"none"
}]]
eItemType = (loadstring or load)(s)() -- since Lua 5.2 loadstring has been replaced by load
for k,v in pairs(eItemType) do
print( k,v)
end
if you need a full copy of a simple table , then it is created like this:
enum = function(t)
local tmp = {}
for _,v in ipairs(t) do tmp[#tmp+1]=v end
return tmp
end
eItemType = enum {
"wpn",
"outf",
"helm",
"art",
"boost",
"bkpk",
"dev",
"ammo",
"none"
}
if you need to move the creation of a global table or enumerations to another place, look at the solution through modules
and the last solution is to get a line of code from a simple table, used to write to a file and generate lua code
function dumpValue(obj)
local s = '\n{ '
for k,v in ipairs(obj) do
s = s .. '\n['..k..'] = "' .. v .. '",'
end
return s .. '} '
end
print(dumpValue(eItemType))

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?
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

Getting "table index is nil" with string index

So I'm currently working on creating blocks of codes which can be called simultaneously by a name id. I've decided to do that with a main table, which contains table with id and with functions. To do that, I wrote 3 functions
function hook.add(name, hookname, func)
hooks[hookname[name]] = func
end
function hook.create(name)
hooks[name] = {}
end
function hook.run(name)
for _, func in pairs(hooks[name]) do
func()
end
end
hook.create("MainHook")
local function func()
print("working")
end
hook.add("todo", "MainHook", func)
However it doesnt work and crashes with
bin/hooks.lua:27: table index is nil
Error contains in
hooks[hookname[name]] = func
line but I have no idea why because even if i print hookname and name there is no nil at all.
I would really appreciate if you help me
Your function hook.create creates empty table for name, so function hook.add should look like this:
function hook.add(name, hookname, func)
-- create hooks[hookname] table if not exists
hooks[hookname] = hooks[hookname] or {}
-- add function to hooks[hookname] table
hooks[hookname][name] = func
end

How to make a class table member distinct in Lua objects?

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.

Catching a call to non existing function in Lua

I'd like to create a simple mock table that would tell me what was tried to be called from it.
My first try was:
local function capture(table, key)
print("call to " .. tostring(table) .. " with key " .. tostring(key))
return key
end
function getMock()
mock = {}
mt = { __index = capture }
setmetatable(mock, mt)
return mock
end
Now calling this with
t = getMock()
t.foo
prints as I expected:
call to table: 002BB188 with key foo
but trying to call:
t.foo("bar")
gives:
call to table: 002BB188 with key foo
lua: test.lua:6: attempt to call field 'foo' (a string value)
Now I have two questions:
How to avoid the exception, ie. what am I doing wrong?
How to catch the method argument too ("bar" in this case)?
You need to return a function from the __index handler, not a string:
local function capture(table, key, rest)
return function(...)
local args = {...}
print(string.format("call to %s with key %s and arg[1] %s",
tostring(table), tostring(key),
tostring(args[1])))
end
end
-- call to table: 0x7fef5b40e310 with key foo and arg[1] nil
-- call to table: 0x7fef5b40e310 with key foo and arg[1] bar
You're getting an error because it's trying to call the result, but it's currently the key.

Resources