hslua-packaging: break up hslua_udnewindex into smaller functions
@@ -140,19 +140,19 @@ int hslua_udindex(lua_State *L)
}
/*
-** Sets a new value in the userdata caching table via a setter
-** functions.
-**
-** The actual assignment is performed by a setter function stored in the
-** `setter` metafield. Throws an error if no setter function can be
-** found.
+** Set value via a property alias. Assumes the stack to be in a state as
+** after __newindex is called. Returns 1 on success, and 0 otherwise.
*/
-int hslua_udnewindex(lua_State *L)
+int hsluaP_set_via_alias(lua_State *L)
{
- /* try aliases */
- if (luaL_getmetafield(L, 1, "aliases") == LUA_TTABLE) {
+ if (luaL_getmetafield(L, 1, "aliases") != LUA_TTABLE) {
+ return 0;
+ }
lua_pushvalue(L, 2);
- if (lua_rawget(L, -2) == LUA_TTABLE) { /* key is an alias */
+ if (lua_rawget(L, -2) != LUA_TTABLE) { /* key is an alias */
+ lua_pop(L, 2);
+ return 0;
+ }
lua_pushvalue(L, 1); /* start with the original object */
/* Iterate over properties; last object is on top of stack,
* list of properties is the second object. */
@@ -164,21 +164,47 @@ int hslua_udnewindex(lua_State *L)
lua_rawgeti(L, -2, lua_rawlen(L, -2)); /* last element */
lua_pushvalue(L, 3); /* new value */
lua_settable(L, -3);
- return 0;
- }
+ return 1;
}
- if (luaL_getmetafield(L, 1, "setters") == LUA_TTABLE) {
+
+/*
+** Set value via a property alias. Assumes the stack to be in a state as
+** after __newindex is called. Returns 1 on success, 0 if the object is
+** readonly, and throws an error if there is no setter for the given
+** key.
+*/
+int hsluaP_set_via_setter(lua_State *L)
+{
+ if (luaL_getmetafield(L, 1, "setters") != LUA_TTABLE)
+ return 0;
+
lua_pushvalue(L, 2); /* key */
- if (lua_rawget(L, -2) == LUA_TFUNCTION) {
+ if (lua_rawget(L, -2) != LUA_TFUNCTION) {
+ lua_pushliteral(L, "Cannot set unknown property.");
+ return lua_error(L);
+ }
+
lua_insert(L, 1);
lua_settop(L, 4); /* 1: setter, 2: ud, 3: key, 4: value */
lua_call(L, 3, 0);
+ return 1;
+}
+
+/*
+** Sets a new value in the userdata caching table via a setter
+** functions.
+**
+** The actual assignment is performed by a setter function stored in the
+** `setter` metafield. Throws an error if no setter function can be
+** found.
+ */
+int hslua_udnewindex(lua_State *L)
+{
+ if (hsluaP_set_via_alias(L) || hsluaP_set_via_setter(L)) {
return 0;
}
- lua_pushliteral(L, "Cannot set unknown property.");
- } else {
+
lua_pushliteral(L, "Cannot modify read-only object.");
- }
return lua_error(L);
}
