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) => { Instruction::GetTable(res, tablereg, indexreg) => {
let value = match self.stack.get(tablereg).cloned() { let value = match self.stack.get(tablereg).cloned() {
Some(value) => { Some(table_value) => {
let table = value.borrow(); let table = table_value.borrow();
if let Value::Table { contents, .. } = &*table { if let Value::Table {
contents,
metatable,
} = &*table
{
let table = contents.borrow(); let table = contents.borrow();
let index_value = self let index_value = self
.stack .stack
.get(indexreg) .get(indexreg)
.map(|v| v.borrow().clone()) .map(|v| v.borrow().clone())
.unwrap_or(Value::Nil) .unwrap_or(Value::Nil);
.as_indexable()?; let value = table.get(&index_value.clone().as_indexable()?);
let value = table.get(&index_value);
match value { match value {
Some(value) => StackValue::Value(value.clone()), 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 { } else {
return Err(RuntimeError::NotTable(table.clone())); return Err(RuntimeError::NotTable(table.clone()));