Rawset function in lua - lua

Rawset function in lua generally is passed table, index and value but I came across this code:
rawset(tbl,name,{})
and
rawset(tbl,name, function() end)
Rawset function returns a table, so what does it mean to have a table or function in rawset function in place for value ?

Lua tables can hold values of all types, including tables and functions, and they can be heterogeneous: not all values need to be of the same type.
See http://www.lua.org/manual/5.2/manual.html#2.1.

From reference manual:
rawset (table, index, value): Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil, and value any Lua value.
What this means:
table's metatable is not used: that's why it is "raw" set, the field is added directly; without raw, the table's metatable will be used to handle the "set" action;
index any value different from nil: in Lua, this really means any type of Lua object other than nil: a number, a function, another table, etc (Lua ref manual lists all types);
value any Lua value: same as previous, but can even be nil: if set to nil, effectively removes item from table.
So index being name just indicates the table is an associative array (unless name is a number but that would be misleading), in first case the associated value is another table, in the second case it is a Lua function.

Related

attempt to call a nil value (method '...') if __index not implemented in metatable

Lua doesn't offer a unique way to OOP.
With setmetatable many alternatives are possible.
Here's what I tried:
Person={}
function Person.__call(cls,name)
return setmetatable({name=name},cls)
end
function Person:say(what)
print(self.name..'> '..what)
end
setmetatable(Person,Person)
p=Person('Fred')
p:say('hello') -- 18
which gives the error:
18: attempt to call a nil value (method 'say')
I can add:
function Person.__index(cls,k)
return Person[k]
end
and then the above code works correctly, however I do not understand why the method is not found when Person is already metatable of itself.
You need to implement the __index metavalue in order to relay indexing access operations. Having a metatable alone is not sufficient.
Also note that it is recommended to implement all meta methods befor using a table as a metatable.
Refer to the Lua 5.4 Reference Manual 2.4 Metatables and Metamethods
__index: The indexing access operation table[key]. This event happens when table is not a table or when key is not present in table. The
metavalue is looked up in the metatable of table.
The metavalue for this event can be either a function, a table, or any
value with an __index metavalue. If it is a function, it is called
with table and key as arguments, and the result of the call (adjusted
to one value) is the result of the operation. Otherwise, the final
result is the result of indexing this metavalue with key. This
indexing is regular, not raw, and therefore can trigger another
__index metavalue.
__index is that metavalue. So if you don't provide that metavalue, what should Lua do?
In the following example that metavalue is Person.
So when I call a:sayName(), Lua will find that a.sayName is nil. It will check if in a's metatable Person there is a __index metavalue. There is and in this case it's a table named Person so it will index that person with key "sayName" which results in the following function call: Person["sayName"](a)
local Person= {}
Person.__index = Person
setmetatable(Person, {
__call = function (cls, ...)
return cls:_init(...)
end,
})
function Person:_init(name)
local o= setmetatable({}, self)
o.name = name
return o
end
function Person:sayName()
print(self.name)
end
local a = Person("Lisa")
a:sayName()

why can you set __index equal to a table

The index metamethod can be set equal to tables. From what I can tell
foo.__index = function(self, k)
return bar[k]
end
and
foo.__index = bar
are the same. Why is declaring functions this way allowed in this situation?
This isn't a function declaration - assigning a table to __index is just a shortcut for using the function that you described.
From Programming in Lua (for Lua 5.0, but this part of the language hasn't changed):
The use of the __index metamethod for inheritance is so common that
Lua provides a shortcut. Despite the name, the __index metamethod does
not need to be a function: It can be a table, instead. When it is a
function, Lua calls it with the table and the absent key as its
arguments. When it is a table, Lua redoes the access in that table.
It's not like the table that you assign magically becomes a function. type(foo.__index) will still return table, and you can still do things with it that you can do with other tables, like using pairs and next, etc.

In Lua, does indexing a table with a table as the key call the __eq metamethod?

I am wondering if table[key] where key is a table with a metatable will call the __eq metamethod. For instance, if the table has a key "a" and the __eq metamethod returns true if "a" is being compared to the metatable, will indexing the table with the table return the value for "a"?
No, indexing uses raw equality: http://www.lua.org/manual/5.2/manual.html#2.4
You should consider explicitly converting your objects to their string representation before indexing instead of relying on implicit metamethods.

Meta tables in lua and_index function

__index = function(tbl, key)
local a = tbl[key]
if a <=0 then a = 0 end
if a > 5 then a = 0 end
return a
end
Book says:
Though the preceding code looks very innocent and tries to keep the value of the element in the table within a range, this code will cause problems and circular references. The first line in the function, a = tbl[key], will actually trigger another index function call, and that in turn will invoke another, and so on.
But how is a = tbl[key] calling another index at every call ?
That is a bit wierd thing to do. Lua triggers __index metamethod only if it can't find a field in the table. Therefore, using tbl[key] inside it makes absolutely no sense at all. Unless tbl is not a table.
Anyhow, if you want to access a table's field from within __index, use rawget. That will ensure that no metamethods are called.
EDIT:
Let me explain how __index lookup works:
Let's assume the table has a metatable with __index defined.
If Lua can't find the key in the table, it looks for the __index field in the metatable. It does not look for the key itself. Then, if the __index is a table, it looks for the key in that table (not the metatable, although it is common to associate the metatable itself with its __index field). If it is a function, it is invoked with two parameters: table (initial table, not the metatable) and the key.
So if the __index metamethod is called, you can be certain that the initial table does not have that field defined. Therefore, when you try to index it again (as the first argument is the original table that triggered the index lookup), the story begins anew -> Lua can't find the key, it invokes the __index and so on.

What's the Javascript 'delete' keyword equivalent in Lua?

Javascript delete keyword deletes a named variable slot from nearest execution environment which it defined.
What's the equivalent in Lua?
var = nil
Environments in Lua are tables, and tables cannot contain nil value - assigning nil to a key in a table effectively deletes that key from the table.
Here is a quote from "Programming in Lua":
Like global variables, table fields
evaluate to nil if they are not
initialized. Also like global
variables, you can assign nil to a
table field to delete it. That is not
a coincidence: Lua stores global
variables in ordinary tables

Resources