If you are using GameMaker Studio 2 or an Early Access version of GameMaker: Studio 1, you can have Lua directly read and write variables on GameMaker instances.
To do so, you would add three scripts to your project:
/// ref_variable_instance_get(context, name)
var q = argument0, s = argument1;
with (q) return variable_instance_get(id, s);
if (q < 100000) {
lua_show_error("Couldn't find any instances of " + string(q)
+ " (" + object_get_name(q) + ")");
} else lua_show_error("Couldn't find instance " + string(q));
return undefined;
(reads a variable from an instance),
/// ref_variable_instance_set(context, name, value)
var q = argument0, s = argument1, v = argument2, n = 0;
with (q) { variable_instance_set(id, s, v); n++; }
if (n) exit;
if (q < 100000) {
lua_show_error("Couldn't find any instances of " + string(q)
+ " (" + object_get_name(q) + ")");
} else lua_show_error("Couldn't find instance " + string(q));
(writes a variable to an instance(s)),
/// ref_variable_instance_init(lua_state)
var q = argument0;
lua_add_function(q, "variable_instance_get", ref_variable_instance_get);
lua_add_function(q, "variable_instance_set", ref_variable_instance_set);
lua_add_code(q, '-- ref_variable_instance_init()
__idfields = __idfields or { };
debug.setmetatable(0, {
__index = function(self, name)
if (__idfields[name]) then
return _G[name];
else
return variable_instance_get(self, name);
end
end,
__newindex = variable_instance_set,
})
');
(exposes the above scripts to a Lua state and sets it up to use them when trying to read/write a field on a numeric value (id)).
Then you can use them as following:
// create a Lua state:
state = lua_state_create();
// allow the state to work with GM instances:
ref_variable_instance_init(state);
// add a test function to the state -
// function takes an instance and modifies it's `result` variable.
lua_add_code(state, "function test(q) q.result = 'Hello!' end");
// call the test-function for the current instance and display the result:
result = "";
lua_call(state, "test", id);
show_debug_message(result);