Add __index metamethod

This commit is contained in:
Sofia 2026-03-21 14:44:25 +02:00
parent 21300b71cf
commit 90c3b90065

View File

@ -599,20 +599,32 @@ impl ClosureRunner {
}
Instruction::GetTable(res, tablereg, indexreg) => {
let value = match self.stack.get(tablereg).cloned() {
Some(value) => {
let table = value.borrow();
if let Value::Table { contents, .. } = &*table {
Some(table_value) => {
let table = table_value.borrow();
if let Value::Table {
contents,
metatable,
} = &*table
{
let table = contents.borrow();
let index_value = self
.stack
.get(indexreg)
.map(|v| v.borrow().clone())
.unwrap_or(Value::Nil)
.as_indexable()?;
let value = table.get(&index_value);
.unwrap_or(Value::Nil);
let value = table.get(&index_value.clone().as_indexable()?);
match value {
Some(value) => StackValue::Value(value.clone()),
None => StackValue::Value(Value::Nil),
None => {
match self.call_metamethod(
metatable,
"__index",
vec![value.unwrap().clone(), index_value.clone()],
) {
Ok(value) => StackValue::Value(value),
Err(_) => StackValue::Value(Value::Nil),
}
}
}
} else {
return Err(RuntimeError::NotTable(table.clone()));