feat: add wrenGetVariable API to load top-level module variable into a slot
Implement wrenGetVariable function in wren_vm.c that looks up a top-level variable by name in a specified module and stores it in the given slot. Includes validation for non-null module/name parameters and slot bounds, module resolution via getModule, variable lookup through symbol table, and slot assignment. Adds corresponding declaration to wren.h public header. Introduces comprehensive test suite in test/api/get_variable.* covering scenarios: retrieving variable before definition (null), after definition, after reassignment, using a non-zero slot, and accessing a variable from another module. Registers the test bindings in test/api/main.c and updates Xcode project file to include the new source.
This commit is contained in:
@@ -384,4 +384,9 @@ void wrenSetSlotValue(WrenVM* vm, int slot, WrenValue* value);
|
||||
// an element, use `-1` for the index.
|
||||
void wrenInsertInList(WrenVM* vm, int listSlot, int index, int elementSlot);
|
||||
|
||||
// Looks up the top level variable with [name] in [module] and stores it in
|
||||
// [slot].
|
||||
void wrenGetVariable(WrenVM* vm, const char* module, const char* name,
|
||||
int slot);
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1789,3 +1789,25 @@ void wrenInsertInList(WrenVM* vm, int listSlot, int index, int elementSlot)
|
||||
|
||||
wrenListInsert(vm, list, vm->foreignStackStart[elementSlot], index);
|
||||
}
|
||||
|
||||
void wrenGetVariable(WrenVM* vm, const char* module, const char* name,
|
||||
int slot)
|
||||
{
|
||||
ASSERT(module != NULL, "Module cannot be NULL.");
|
||||
ASSERT(module != NULL, "Variable name cannot be NULL.");
|
||||
validateForeignSlot(vm, slot);
|
||||
|
||||
Value moduleName = wrenStringFormat(vm, "$", module);
|
||||
wrenPushRoot(vm, AS_OBJ(moduleName));
|
||||
|
||||
ObjModule* moduleObj = getModule(vm, moduleName);
|
||||
ASSERT(moduleObj != NULL, "Could not find module.");
|
||||
|
||||
wrenPopRoot(vm); // moduleName.
|
||||
|
||||
int variableSlot = wrenSymbolTableFind(&moduleObj->variableNames,
|
||||
name, strlen(name));
|
||||
ASSERT(variableSlot != -1, "Could not find variable.");
|
||||
|
||||
setSlot(vm, slot, moduleObj->variables.data[variableSlot]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user