How to access vector components? #1298
-
If I pass a vector to a Luau script with lua_pushvector(script.thread_state, 1.0, 2.0, 3.0); v.x etc. doesn't work. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Ok looks like v.x does work usually, there is some issue when accessing a global vector (sandboxing?) |
Beta Was this translation helpful? Give feedback.
-
Currently, Luau doesn't come with a full vector library/metatable setup. To setup basic x/y/z access, you can do the following: static int lua_vector_index(lua_State* L)
{
const float* v = luaL_checkvector(L, 1);
const char* name = luaL_checkstring(L, 2);
int ic = (name[0]) - 'x';
if (unsigned(ic) < 3 && name[1] == '\0')
{
lua_pushnumber(L, v[ic]);
return 1;
}
luaL_error(L, "%s is not a valid member of vector", name);
}
static int lua_vector_namecall(lua_State* L)
{
luaL_error(L, "%s is not a valid method of vector", luaL_checkstring(L, 1));
}
void setupVectorHelpers(lua_State* L)
{
lua_pushvector(L, 0.0f, 0.0f, 0.0f);
luaL_newmetatable(L, "vector");
lua_pushcfunction(L, lua_vector_index, nullptr);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_vector_namecall, nullptr);
lua_setfield(L, -2, "__namecall");
lua_setreadonly(L, -1, true);
lua_setmetatable(L, -2);
lua_pop(L, 1);
} Index and namecall handlers can be extended with additional properties and methods. |
Beta Was this translation helpful? Give feedback.
-
Ok, thanks. |
Beta Was this translation helpful? Give feedback.
Currently, Luau doesn't come with a full vector library/metatable setup.
Only one access method has a fast-path included in the interpreter loop for performance.
To setup basic x/y/z access, you can do the following: