Esempio n. 1
0
void push_luapacket(lua_State *L,packet_t pk){
	lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p));
	luaL_getmetatable(L, LUAPACKET_METATABLE);
	lua_setmetatable(L, -2);
	p->_packet = pk;
}
Esempio n. 2
0
/*
** Define the metatable for the object on top of the stack
*/
LUACRYPTO_API void luacrypto_setmeta (lua_State *L, const char *name) {
  luaL_getmetatable (L, name);
  lua_setmetatable (L, -2);
}
Esempio n. 3
0
int luaopen_cairo( lua_State* L )
{
  static const luaL_reg methods[] = {
    {"__gc", cairo__gc_l},
    {"destroy", cairo_destroy_l},
    {"save", cairo_save_l},
    {"restore", cairo_restore_l},
    {"push_group", cairo_push_group_l},
    {"push_group_with_content", cairo_push_group_with_content_l},
    {"pop_group", cairo_pop_group_l},
    {"pop_group_to_source", cairo_pop_group_to_source_l},
    {"set_source_rgb", cairo_set_source_rgb_l},
    {"set_source_rgba", cairo_set_source_rgba_l},
    {"set_source", cairo_set_source_l},
    {"set_source_surface", cairo_set_source_surface_l},
    {"get_source", cairo_get_source_l},
    {"set_antialias", cairo_set_antialias_l},
    {"get_antialias", cairo_get_antialias_l},
    {"set_dash", cairo_set_dash_l},
    {"get_dash_count", cairo_get_dash_count_l},
    {"get_dash", cairo_get_dash_l},
    {"set_line_cap", cairo_set_line_cap_l},
    {"get_line_cap", cairo_get_line_cap_l},
    {"set_line_join", cairo_set_line_join_l},
    {"get_line_join", cairo_get_line_join_l},
    {"set_line_width", cairo_set_line_width_l},
    {"get_line_width", cairo_get_line_width_l},
    {"set_miter_limit", cairo_set_miter_limit_l},
    {"get_miter_limit", cairo_get_miter_limit_l},
    {"set_operator", cairo_set_operator_l},
    {"get_operator", cairo_get_operator_l},
    {"clip", cairo_clip_l},
    {"clip_preserve", cairo_clip_preserve_l},
    {"clip_extents", cairo_clip_extents_l},
    {"in_clip", cairo_in_clip_l},
    {"reset_clip", cairo_reset_clip_l},
    {"fill", cairo_fill_l},
    {"fill_preserve", cairo_fill_preserve_l},
    {"fill_extents", cairo_fill_extents_l},
    {"in_fill", cairo_in_fill_l},
    {"mask", cairo_mask_l},
    {"mask_surface", cairo_mask_surface_l},
    {"paint", cairo_paint_l},
    {"paint_with_alpha", cairo_paint_with_alpha_l},
    {"stroke", cairo_stroke_l},
    {"stroke_preserve", cairo_stroke_preserve_l},
    {"stroke_extents", cairo_stroke_extents_l},
    {"in_stroke", cairo_in_stroke_l},
    {"new_path", cairo_new_path_l},
    {"new_sub_path", cairo_new_sub_path_l},
    {"close_path", cairo_close_path_l},
    {"arc", cairo_arc_l},
    {"arc_negative", cairo_arc_negative_l},
    {"curve_to", cairo_curve_to_l},
    {"line_to", cairo_line_to_l},
    {"move_to", cairo_move_to_l},
    {"rectangle", cairo_rectangle_l},
    {"text_path", cairo_text_path_l},
    {"rel_curve_to", cairo_rel_curve_to_l},
    {"rel_line_to", cairo_rel_line_to_l},
    {"rel_move_to", cairo_rel_move_to_l},
    {"path_extents", cairo_path_extents_l},
    {"set_font_size", cairo_set_font_size_l},
    {"set_font_options", cairo_set_font_options_l},
    {"get_font_options", cairo_get_font_options_l},
    {"set_font_face", cairo_set_font_face_l},
    {"show_text", cairo_show_text_l},
    {"font_extents", cairo_font_extents_l},
    {"text_extents", cairo_text_extents_l},
    {"translate", cairo_translate_l},
    {"scale", cairo_scale_l},
    {"rotate", cairo_rotate_l},
    {"identity_matrix", cairo_identity_matrix_l},
    {0, 0}
  };

  static const luaL_reg cairo[] = {
    {"create", cairo_create_l},
    {"destroy", cairo_destroy_l},
    {0, 0}
  };

  luaL_newmetatable( L, "lua_cairo_t" );
  lua_pushvalue( L, -1 ); /* duplicate the metatable */
  lua_setfield( L, -2, "__index" ); /* set the metamethod to the metatable */

  luaL_register( L, 0, methods ); /* pack the methods in the metatable */
  lua_pop( L, 1 );

  luaL_register( L, "cairo", cairo );
  luaL_getmetatable(L, "lua_cairo_t");
  lua_setfield(L, -2, "crmetatable");

  luaopen_cairo_surface( L );
  luaopen_cairo_pattern( L );
  luaopen_cairo_font( L );

  return( 1 );
}
Esempio n. 4
0
void push_cpArbiter(lua_State *L, cpArbiter *arb) {
    cpArbiter **ptr = (cpArbiter **)lua_newuserdata(L, sizeof(cpArbiter *));
    *ptr = arb;
    luaL_getmetatable(L, "cpArbiter");
    lua_setmetatable(L, -2);
}
static int lua_PhysicsFixedConstraint_static_getTranslationOffset(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 2:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL) &&
                (lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL))
            {
                // Get parameter 1 off the stack.
                bool param1Valid;
                gameplay::ScriptUtil::LuaArray<Node> param1 = gameplay::ScriptUtil::getObjectPointer<Node>(1, "Node", false, &param1Valid);
                if (!param1Valid)
                {
                    lua_pushstring(state, "Failed to convert parameter 1 to type 'Node'.");
                    lua_error(state);
                }

                // Get parameter 2 off the stack.
                bool param2Valid;
                gameplay::ScriptUtil::LuaArray<Vector3> param2 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, &param2Valid);
                if (!param2Valid)
                {
                    lua_pushstring(state, "Failed to convert parameter 2 to type 'Vector3'.");
                    lua_error(state);
                }

                void* returnPtr = (void*)new Vector3(PhysicsFixedConstraint::getTranslationOffset(param1, *param2));
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = true;
                    luaL_getmetatable(state, "Vector3");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_PhysicsFixedConstraint_static_getTranslationOffset - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 2).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Esempio n. 6
0
int l_kvsdir_instantiate (lua_State *L)
{
    luaL_getmetatable (L, "CMB.kvsdir");
    lua_setmetatable (L, -2);
    return (1);
}
int lua_VertexAttributeBinding_static_create(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 2:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL) &&
                (lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TTABLE || lua_type(state, 2) == LUA_TNIL))
            {
                // Get parameter 1 off the stack.
                bool param1Valid;
                ScriptUtil::LuaArray<Mesh> param1 = ScriptUtil::getObjectPointer<Mesh>(1, "Mesh", false, &param1Valid);
                if (!param1Valid)
                {
                    lua_pushstring(state, "Failed to convert parameter 1 to type 'Mesh'.");
                    lua_error(state);
                }

                // Get parameter 2 off the stack.
                bool param2Valid;
                ScriptUtil::LuaArray<Effect> param2 = ScriptUtil::getObjectPointer<Effect>(2, "Effect", false, &param2Valid);
                if (!param2Valid)
                {
                    lua_pushstring(state, "Failed to convert parameter 2 to type 'Effect'.");
                    lua_error(state);
                }

                void* returnPtr = (void*)VertexAttributeBinding::create(param1, param2);
                if (returnPtr)
                {
                    ScriptUtil::LuaObject* object = (ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = true;
                    luaL_getmetatable(state, "VertexAttributeBinding");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_VertexAttributeBinding_static_create - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 2).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Esempio n. 8
0
/*-------------------------------------------------------------------------*\
* Set object class
\*-------------------------------------------------------------------------*/
void auxiliar_setclass(lua_State *L, const char *classname, int objidx) {
    luaL_getmetatable(L, classname);
    if (objidx < 0) objidx--;
    lua_setmetatable(L, objidx);
}
Esempio n. 9
0
// get_mapgen_object(objectname)
// returns the requested object used during map generation
int ModApiMapgen::l_get_mapgen_object(lua_State *L)
{
	const char *mgobjstr = lua_tostring(L, 1);

	int mgobjint;
	if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : ""))
		return 0;

	enum MapgenObject mgobj = (MapgenObject)mgobjint;

	EmergeManager *emerge = getServer(L)->getEmergeManager();
	Mapgen *mg = emerge->getCurrentMapgen();
	if (!mg)
		return 0;

	size_t maplen = mg->csize.X * mg->csize.Z;

	switch (mgobj) {
	case MGOBJ_VMANIP: {
		MMVManip *vm = mg->vm;

		// VoxelManip object
		LuaVoxelManip *o = new LuaVoxelManip(vm, true);
		*(void **)(lua_newuserdata(L, sizeof(void *))) = o;
		luaL_getmetatable(L, "VoxelManip");
		lua_setmetatable(L, -2);

		// emerged min pos
		push_v3s16(L, vm->m_area.MinEdge);

		// emerged max pos
		push_v3s16(L, vm->m_area.MaxEdge);

		return 3;
	}
	case MGOBJ_HEIGHTMAP: {
		if (!mg->heightmap)
			return 0;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushinteger(L, mg->heightmap[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}
	case MGOBJ_BIOMEMAP: {
		if (!mg->biomemap)
			return 0;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushinteger(L, mg->biomemap[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}
	case MGOBJ_HEATMAP: { // Mapgen V7 specific objects
	case MGOBJ_HUMIDMAP:
		if (strcmp(emerge->params.mg_name.c_str(), "v7"))
			return 0;

		MapgenV7 *mgv7 = (MapgenV7 *)mg;

		float *arr = (mgobj == MGOBJ_HEATMAP) ?
			mgv7->noise_heat->result : mgv7->noise_humidity->result;
		if (!arr)
			return 0;

		lua_newtable(L);
		for (size_t i = 0; i != maplen; i++) {
			lua_pushnumber(L, arr[i]);
			lua_rawseti(L, -2, i + 1);
		}

		return 1;
	}
	case MGOBJ_GENNOTIFY: {
		std::map<std::string, std::vector<v3s16> >event_map;
		std::map<std::string, std::vector<v3s16> >::iterator it;

		mg->gennotify.getEvents(event_map);

		lua_newtable(L);
		for (it = event_map.begin(); it != event_map.end(); ++it) {
			lua_newtable(L);

			for (size_t j = 0; j != it->second.size(); j++) {
				push_v3s16(L, it->second[j]);
				lua_rawseti(L, -2, j + 1);
			}

			lua_setfield(L, -2, it->first.c_str());
		}

		return 1;
	}
	}

	return 0;
}
Esempio n. 10
0
static int LUA_C_tcp_new(lua_State* ls)
  {
  xWSA wsa;
  SOCKET sock = socket(PF_INET, SOCK_STREAM, 0);
  if(sock == INVALID_SOCKET)
    {
    xmsg msg;
    msg << "建立tcp socket失败:" << WSAGetLastError();
    lua_pushstring(ls, msg.c_str());
    return lua_error(ls);
    }
  if(lua_type(ls, 1) == LUA_TNUMBER)
    {
    sockaddr_in addr;
    addr.sin_addr.s_addr = lua_tointeger(ls, 1);
    xmsg msg;
    msg
      << (int)addr.sin_addr.s_net << '.'
      << (int)addr.sin_addr.s_host << '.'
      << (int)addr.sin_addr.s_lh << '.'
      << (int)addr.sin_addr.s_impno;
    lua_pushstring(ls, msg.c_str());
    lua_replace(ls, 1);
    }
  auto ip = luaL_optstring(ls, 1, "0.0.0.0");
  auto port = luaL_optstring(ls, 2, "0");

  auto bind_port = luaL_optinteger(ls, 3, 0);

  try
    {
    auto addr = AddrInfo(ip, port);

    if(bind_port != 0)
      {
      auto s = AddrInfo(INADDR_ANY, bind_port);
      if(bind(sock, (sockaddr*)&s, sizeof(s)))
        {
        shutdown(sock, SD_BOTH);
        closesocket(sock);
        xmsg msg;
        msg << "tcp socket绑定[" << (intptr_t)htons(addr.sin_port)
          << "]失败:" << (intptr_t)WSAGetLastError();
        lua_pushstring(ls, msg.c_str());
        return lua_error(ls);
        }
      if(listen(sock, 0))
        {
        shutdown(sock, SD_BOTH);
        closesocket(sock);
        xmsg msg;
        msg << "tcp socket监听[" << (intptr_t)htons(addr.sin_port)
          << "]失败:" << (intptr_t)WSAGetLastError();
        lua_pushstring(ls, msg.c_str());
        return lua_error(ls);
        }
      }
    else
      {
      if(addr.sin_addr.S_un.S_addr == INADDR_ANY || addr.sin_port == 0)
        {
        lua_pushstring(ls, "tcp socket 请明确指定连接的地址、端口");
        return lua_error(ls);
        }
      if(connect(sock, (sockaddr*)&addr, sizeof(addr)))
        {
        shutdown(sock, SD_BOTH);
        closesocket(sock);
        xmsg msg;
        msg << "tcp socket连接[" << IpString(addr)
          << "]失败:" << (intptr_t)WSAGetLastError();
        lua_pushstring(ls, msg.c_str());
        return lua_error(ls);
        }
      }

    luaL_getmetatable(ls, gk_tcp_register);
    if(lua_type(ls, -1) == LUA_TNIL)
      {
      lua_pop(ls, 1);
      luaL_newmetatable(ls, gk_tcp_register);
      lua_pushvalue(ls, -1);
      lua_setfield(ls, -2, "__index");
      luaL_setfuncs(ls, gkTCPLib, 0);
      lua_pop(ls, 1);
      }
    else
      {
      lua_pop(ls, 1);
      }

    SOCKET_ST* st = (SOCKET_ST*)lua_newuserdata(ls, sizeof(*st));
    st->sock = sock;
    st->addr = addr;
    st->bind_port = bind_port;

    luaL_setmetatable(ls, gk_tcp_register);
    return 1;
    }
  catch(const runtime_error& err)
    {
    shutdown(sock, SD_BOTH);
    closesocket(sock);
    xmsg msg;
    msg << "建立TCP错误:" << err.what();
    lua_pushstring(ls, msg.c_str());
    return lua_error(ls);
    }
  catch(...)
    {
    shutdown(sock, SD_BOTH);
    closesocket(sock);
    lua_pushstring(ls, "建立TCP异常");
    return lua_error(ls);
    }
  }
Esempio n. 11
0
static int lua_TileSet_static_create(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TTABLE || lua_type(state, 1) == LUA_TNIL))
                {
                    // Get parameter 1 off the stack.
                    bool param1Valid;
                    gameplay::ScriptUtil::LuaArray<Properties> param1 = gameplay::ScriptUtil::getObjectPointer<Properties>(1, "Properties", false, &param1Valid);
                    if (!param1Valid)
                        break;

                    void* returnPtr = ((void*)TileSet::create(param1));
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = false;
                        luaL_getmetatable(state, "TileSet");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_TileSet_static_create - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        case 5:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TSTRING || lua_type(state, 1) == LUA_TNIL) &&
                    lua_type(state, 2) == LUA_TNUMBER &&
                    lua_type(state, 3) == LUA_TNUMBER &&
                    lua_type(state, 4) == LUA_TNUMBER &&
                    lua_type(state, 5) == LUA_TNUMBER)
                {
                    // Get parameter 1 off the stack.
                    const char* param1 = gameplay::ScriptUtil::getString(1, false);

                    // Get parameter 2 off the stack.
                    float param2 = (float)luaL_checknumber(state, 2);

                    // Get parameter 3 off the stack.
                    float param3 = (float)luaL_checknumber(state, 3);

                    // Get parameter 4 off the stack.
                    unsigned int param4 = (unsigned int)luaL_checkunsigned(state, 4);

                    // Get parameter 5 off the stack.
                    unsigned int param5 = (unsigned int)luaL_checkunsigned(state, 5);

                    void* returnPtr = ((void*)TileSet::create(param1, param2, param3, param4, param5));
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = false;
                        luaL_getmetatable(state, "TileSet");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_TileSet_static_create - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1 or 5).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Esempio n. 12
0
int lua_TerrainPatch_getMaterial(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA))
            {
                TerrainPatch* instance = getInstance(state);
                void* returnPtr = (void*)instance->getMaterial();
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = false;
                    luaL_getmetatable(state, "Material");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_TerrainPatch_getMaterial - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        case 2:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                lua_type(state, 2) == LUA_TNUMBER)
            {
                // Get parameter 1 off the stack.
                int param1 = (int)luaL_checkint(state, 2);

                TerrainPatch* instance = getInstance(state);
                void* returnPtr = (void*)instance->getMaterial(param1);
                if (returnPtr)
                {
                    gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = false;
                    luaL_getmetatable(state, "Material");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_TerrainPatch_getMaterial - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Esempio n. 13
0
void *luabridge::checkclass (lua_State *L, int idx, const char *tname,
	bool exact)
{
	// If idx is relative to the top of the stack, convert it into an index
	// relative to the bottom of the stack, so we can push our own stuff
	if (idx < 0)
		idx += lua_gettop(L) + 1;

	int top = lua_gettop(L);

	// Check that the thing on the stack is indeed a userdata
	if (!lua_isuserdata(L, idx))
		luaL_typerror(L, idx, tname);

	// Lookup the given name in the registry
	luaL_getmetatable(L, tname);

	// Lookup the metatable of the given userdata
	lua_getmetatable(L, idx);
	
	// If exact match required, simply test for identity.
	if (exact)
	{
		// Ignore "const" for exact tests (which are used for destructors).
		if (!strncmp(tname, "const ", 6))
			tname += 6;

		if (lua_rawequal(L, -1, -2))
			return lua_touserdata(L, idx);
		else
		{
			// Generate an informative error message
			rawgetfield(L, -1, "__type");
			char buffer[256];
			snprintf(buffer, 256, "%s expected, got %s", tname,
				lua_tostring(L, -1));
			// luaL_argerror does not return
			luaL_argerror(L, idx, buffer);
			return 0;
		}
	}

	// Navigate up the chain of parents if necessary
	while (!lua_rawequal(L, -1, -2))
	{
		// Check for equality to the const metatable
		rawgetfield(L, -1, "__const");
		if (!lua_isnil(L, -1))
		{
			if (lua_rawequal(L, -1, -3))
				break;
		}
		lua_pop(L, 1);

		// Look for the metatable's parent field
		rawgetfield(L, -1, "__parent");

		// No parent field?  We've failed; generate appropriate error
		if (lua_isnil(L, -1))
		{
			// Lookup the __type field of the original metatable, so we can
			// generate an informative error message
			lua_getmetatable(L, idx);
			rawgetfield(L, -1, "__type");

			char buffer[256];
			snprintf(buffer, 256, "%s expected, got %s", tname,
				lua_tostring(L, -1));
			// luaL_argerror does not return
			luaL_argerror(L, idx, buffer);
			return 0;
		}

		// Remove the old metatable from the stack
		lua_remove(L, -2);
	}
	
	lua_settop(L, top);
	// Found a matching metatable; return the userdata
	return lua_touserdata(L, idx);
}
Esempio n. 14
0
static int l_Quaternion_index(lua_State *L) {
  Quaternion* quaternion = lua_toquaternion(L, 1);

  auto numargs = lua_gettop(L);
  if (numargs > 2) {
    luaL_error(L, "LUA_ERROR: Wrong number of arguments, %d provided",
	       numargs);
  }
  if (lua_isnumber(L, 2)) {
    integerType index = lua_tointeger(L, 2);
    lua_pop(L, 1);
    
    if (index < 1 || index > 4) {
      luaL_error(L, "LUA_ERROR: Index out of range --> %d", index);
    }

    switch(index) {
    case 1:
      lua_pushnumber(L, quaternion->w);
      break;
    case 2:
      lua_pushnumber(L, quaternion->v.x);
      break;
    case 3:
      lua_pushnumber(L, quaternion->v.y);
      break;
    case 4:
      lua_pushnumber(L, quaternion->v.z);
      break;
    }

    return 1;
  }
  else if (lua_isstring(L, 2)) {
    stringType sIndex = lua_tostring(L, 2);
    if (sIndex == "w") {
      lua_pushnumber(L, quaternion->w);
    }
    else if (sIndex == "x") {
      lua_pushnumber(L, quaternion->v.x);
    }
    else if (sIndex == "y") {
      lua_pushnumber(L, quaternion->v.y);
    }
    else if (sIndex == "z") {
      lua_pushnumber(L, quaternion->v.z);
    }
    else {
      //get the metafields
      luaL_getmetatable(L, LUA_USERDATA_QUATERNION);
      lua_getfield(L, -1, sIndex.c_str());
    }

    return 1;
  }
  else {
    luaL_error(L, "LUA_ERROR: Incorrect type");
    return 0;
  }
  return 0;
}
Esempio n. 15
0
TOLUA_API void tolua_pushusertype (lua_State* L, void* value, const char* type)
{
    if (value == NULL)
        lua_pushnil(L);
    else
    {        
        luaL_getmetatable(L, type);                                 /* stack: mt */
        if (lua_isnil(L, -1)) { /* NOT FOUND metatable */
            lua_pop(L, 1);
            return;
        }
        lua_pushstring(L,"tolua_ubox");
        lua_rawget(L,-2);                                           /* stack: mt ubox */
        if (lua_isnil(L, -1)) {
            lua_pop(L, 1);
            lua_pushstring(L, "tolua_ubox");
            lua_rawget(L, LUA_REGISTRYINDEX);
        };
        
        lua_pushlightuserdata(L,value);                             /* stack: mt ubox key<value> */
        lua_rawget(L,-2);                                           /* stack: mt ubox ubox[value] */
        
        if (lua_isnil(L,-1))
        {
            lua_pop(L,1);                                           /* stack: mt ubox */
            lua_pushlightuserdata(L,value);
            *(void**)lua_newuserdata(L,sizeof(void *)) = value;     /* stack: mt ubox value newud */
            lua_pushvalue(L,-1);                                    /* stack: mt ubox value newud newud */
            lua_insert(L,-4);                                       /* stack: mt newud ubox value newud */
            lua_rawset(L,-3);                  /* ubox[value] = newud, stack: mt newud ubox */
            lua_pop(L,1);                                           /* stack: mt newud */
            /*luaL_getmetatable(L,type);*/
            lua_pushvalue(L, -2);                                   /* stack: mt newud mt */
            lua_setmetatable(L,-2);                      /* update mt, stack: mt newud */

#ifdef LUA_VERSION_NUM
            lua_pushvalue(L, TOLUA_NOPEER);
            lua_setfenv(L, -2);
#endif
        }
        else
        {
            /* check the need of updating the metatable to a more specialized class */
            lua_insert(L,-2);                                       /* stack: mt ubox[u] ubox */
            lua_pop(L,1);                                           /* stack: mt ubox[u] */
            lua_pushstring(L,"tolua_super");
            lua_rawget(L,LUA_REGISTRYINDEX);                        /* stack: mt ubox[u] super */
            lua_getmetatable(L,-2);                                 /* stack: mt ubox[u] super mt */
            lua_rawget(L,-2);                                       /* stack: mt ubox[u] super super[mt] */
            if (lua_istable(L,-1))
            {
                lua_pushstring(L,type);                             /* stack: mt ubox[u] super super[mt] type */
                lua_rawget(L,-2);                                   /* stack: mt ubox[u] super super[mt] flag */
                if (lua_toboolean(L,-1) == 1)                       /* if true */
                {
                    lua_pop(L,3);                                   /* mt ubox[u]*/
                    lua_remove(L, -2);
                    return;
                }
            }
            /* type represents a more specilized type */
            /*luaL_getmetatable(L,type);             // stack: mt ubox[u] super super[mt] flag mt */
            lua_pushvalue(L, -5);					/* stack: mt ubox[u] super super[mt] flag mt */
            lua_setmetatable(L,-5);                /* stack: mt ubox[u] super super[mt] flag */
            lua_pop(L,3);                          /* stack: mt ubox[u] */
        }
        lua_remove(L, -2);	/* stack: ubox[u]*/
    }
}
Esempio n. 16
0
/*
 * Returns: [interfaces (table)]
 */
static int
sock_getifaddrs (lua_State *L)
{
  struct sock_addr *sap;
  int i, res;

#ifndef _WIN32
  struct ifaddrs *result, *rp;

  sys_vm_leave(L);
  res = getifaddrs(&result);
  sys_vm_enter(L);
#else
  INTERFACE_INFO result[8192], *rp;
  SOCKET sd = WSASocketW(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAGS);
  DWORD n;

  sys_vm_leave(L);
  res = WSAIoctl(sd, SIO_GET_INTERFACE_LIST, NULL, 0,
   result, sizeof(result), &n, NULL, NULL);

  closesocket(sd);
  sys_vm_enter(L);
#endif

  if (res == -1)
    return sys_seterror(L, 0);

  lua_createtable(L, 8, 0);
  rp = result;
#ifndef _WIN32
  for (i = 0; rp; rp = rp->ifa_next) {
#else
  for (i = 0; n--; ++rp) {
#endif
#ifndef _WIN32
    sap = (struct sock_addr *) rp->ifa_addr;
#else
    sap = (struct sock_addr *) &rp->iiAddress;
#endif
    if (!sap || sap->u.addr.sa_family == AF_UNSPEC)
      continue;

    lua_newtable(L);
    {
      const int af = sap->u.addr.sa_family;

      if (af == AF_INET
#ifdef AF_INET6
       || af == AF_INET6
#endif
      ) {
        sock_pushaddr(L, sap);
        lua_setfield(L, -2, "addr");
      }

      {
        const char *s = NULL;

        switch (af) {
        case AF_INET: s = "INET"; break;
#ifdef AF_INET6
        case AF_INET6: s = "INET6"; break;
#endif
#ifdef AF_LOCAL
        case AF_LOCAL: s = "LOCAL"; break;
#endif
#ifdef AF_AX25
        case AF_AX25: s = "AX25"; break;
#endif
#ifdef AF_IPX
        case AF_IPX: s = "IPX"; break;
#endif
#ifdef AF_APPLETALK
        case AF_APPLETALK: s = "APPLETALK"; break;
#endif
#ifdef AF_NETROM
        case AF_NETROM: s = "NETROM"; break;
#endif
#ifdef AF_BRIDGE
        case AF_BRIDGE: s = "BRIDGE"; break;
#endif
#ifdef AF_ATMPVC
        case AF_ATMPVC: s = "ATMPVC"; break;
#endif
#ifdef AF_X25
        case AF_X25: s = "X25"; break;
#endif
#ifdef AF_ROSE
        case AF_ROSE: s = "ROSE"; break;
#endif
#ifdef AF_DECnet
        case AF_DECnet: s = "DECnet"; break;
#endif
#ifdef AF_NETBEUI
        case AF_NETBEUI: s = "NETBEUI"; break;
#endif
#ifdef AF_SECURITY
        case AF_SECURITY: s = "SECURITY"; break;
#endif
#ifdef AF_KEY
        case AF_KEY: s = "KEY"; break;
#endif
#ifdef AF_NETLINK
        case AF_NETLINK: s = "NETLINK"; break;
#endif
#ifdef AF_PACKET
        case AF_PACKET: s = "PACKET"; break;
#endif
#ifdef AF_ASH
        case AF_ASH: s = "ASH"; break;
#endif
#ifdef AF_ECONET
        case AF_ECONET: s = "ECONET"; break;
#endif
#ifdef AF_ATMSVC
        case AF_ATMSVC: s = "ATMSVC"; break;
#endif
#ifdef AF_RDS
        case AF_RDS: s = "RDS"; break;
#endif
#ifdef AF_SNA
        case AF_SNA: s = "SNA"; break;
#endif
#ifdef AF_IRDA
        case AF_IRDA: s = "IRDA"; break;
#endif
#ifdef AF_PPPOX
        case AF_PPPOX: s = "PPPOX"; break;
#endif
#ifdef AF_WANPIPE
        case AF_WANPIPE: s = "WANPIPE"; break;
#endif
#ifdef AF_LLC
        case AF_LLC: s = "LLC"; break;
#endif
#ifdef AF_CAN
        case AF_CAN: s = "CAN"; break;
#endif
#ifdef AF_TIPC
        case AF_TIPC: s = "TIPC"; break;
#endif
#ifdef AF_BLUETOOTH
        case AF_BLUETOOTH: s = "BLUETOOTH"; break;
#endif
#ifdef AF_IUCV
        case AF_IUCV: s = "IUCV"; break;
#endif
#ifdef AF_RXRPC
        case AF_RXRPC: s = "RXRPC"; break;
#endif
#ifdef AF_ISDN
        case AF_ISDN: s = "ISDN"; break;
#endif
#ifdef AF_PHONET
        case AF_PHONET: s = "PHONET"; break;
#endif
#ifdef AF_IEEE802154
        case AF_IEEE802154: s = "IEEE802154"; break;
#endif
        default: s = "UNKNOWN";
        }
        if (s) {
          lua_pushstring(L, s);
          lua_setfield(L, -2, "family");
        }
      }

#ifndef _WIN32
      sap = (struct sock_addr *) rp->ifa_netmask;
#else
      sap = (struct sock_addr *) &rp->iiNetmask;
#endif
      if (sap) {
        sock_pushaddr(L, sap);
        lua_setfield(L, -2, "netmask");
      }

#ifndef _WIN32
      sap = (struct sock_addr *) rp->ifa_broadaddr;
#else
      sap = (struct sock_addr *) &rp->iiBroadcastAddress;
#endif
      if (sap) {
        sock_pushaddr(L, sap);
        lua_setfield(L, -2, "broadaddr");
      }

      lua_createtable(L, 0, 5);
      {
#ifndef _WIN32
        const int flags = rp->ifa_flags;
#else
        const int flags = rp->iiFlags;
#endif

        lua_pushboolean(L, flags & IFF_UP);
        lua_setfield(L, -2, "up");

        lua_pushboolean(L, flags & IFF_BROADCAST);
        lua_setfield(L, -2, "broadcast");

        lua_pushboolean(L, flags & IFF_LOOPBACK);
        lua_setfield(L, -2, "loopback");

        lua_pushboolean(L, flags & IFF_POINTOPOINT);
        lua_setfield(L, -2, "pointtopoint");

        lua_pushboolean(L, flags & IFF_MULTICAST);
        lua_setfield(L, -2, "multicast");
      }
      lua_setfield(L, -2, "flags");
    }
    lua_rawseti(L, -2, ++i);
  }
#ifndef _WIN32
  freeifaddrs(result);
#endif
  return 1;
}


/*
 * Arguments: text_address (string), [ip4_tonumber (true)]
 * Returns: [binary_address (string | number)]
 */
static int
sock_inet_pton (lua_State *L)
{
  const char *src = luaL_checkstring(L, 1);
  const int to_ip4 = lua_toboolean(L, 2);
  const int af = (!to_ip4 && strchr(src, ':')) ? AF_INET6 : AF_INET;
  struct sock_addr sa;
  void *inp = sock_addr_get_inp(&sa, af);
  const int in_len = sock_addr_get_inlen(af);
#ifdef _WIN32
  union sys_rwptr src_ptr;  /* to avoid "const cast" warning */
#endif

  memset(&sa, 0, sizeof(struct sock_addr));
  if (*src == '*') goto end;

#ifndef _WIN32
  if (inet_pton(af, src, inp) == 1) {
#else
  sa.addrlen = sizeof(sa);
  src_ptr.r = src;
  if (!WSAStringToAddressA(src_ptr.w, af, NULL,
   &sa.u.addr, &sa.addrlen)) {
#endif
 end:
    if (to_ip4)
      lua_pushnumber(L, ntohl(*((unsigned long *) inp)));
    else
      lua_pushlstring(L, inp, in_len);
    return 1;
  }
  return sys_seterror(L, 0);
}

/*
 * Arguments: binary_address (string | number)
 * Returns: [text_address (string)]
 */
static int
sock_inet_ntop (lua_State *L)
{
  const int is_ip4 = (lua_type(L, 1) == LUA_TNUMBER);
  unsigned long ip4;
  int in_len, af;
  const char *src;
  char buf[48];

  if (is_ip4) {
    const lua_Number num = lua_tonumber(L, 1);

    in_len = 4;
    af = AF_INET;
    ip4 = htonl((unsigned long) num);
    src = (const char *) &ip4;
  } else {
    src = sock_checkladdr(L, 1, &in_len, &af);
  }

#ifndef _WIN32
  if (inet_ntop(af, src, buf, sizeof(buf)) == NULL)
    goto err;
#else
  {
    struct sock_addr sa;
    void *inp = sock_addr_get_inp(&sa, af);
    const int sl = (af == AF_INET) ? sizeof(struct sockaddr_in)
     : sizeof(struct sockaddr_in6);
    DWORD buflen = sizeof(buf);

    memset(&sa, 0, sizeof(struct sock_addr));
    memcpy(inp, src, in_len);
    sa.u.addr.sa_family = (short) af;

    if (WSAAddressToStringA(&sa.u.addr, sl, NULL, buf, &buflen)
     || buflen >= sizeof(buf))
      goto err;
  }
#endif
  lua_pushstring(L, buf);
  return 1;
 err:
  return sys_seterror(L, 0);
}


/*
 * Returns: sock_addr_udata
 */
static int
sock_addr_new (lua_State *L)
{
  lua_newuserdata(L, sizeof(struct sock_addr));
  luaL_getmetatable(L, SA_TYPENAME);
  lua_setmetatable(L, -2);
  return 1;
}

/*
 * Arguments: sock_addr_udata, [port (number), binary_address (string)]
 * Returns: sock_addr_udata | port (number), binary_address (string)
 */
static int
sock_addr_inet (lua_State *L)
{
  struct sock_addr *sap = checkudata(L, 1, SA_TYPENAME);

  if (lua_gettop(L) == 1) {
    const int af = sap->u.addr.sa_family;

    if (af == AF_INET) {
      lua_pushinteger(L, ntohs(sap->u.in.sin_port));
      lua_pushlstring(L, (char *) &sap->u.in.sin_addr,
       sizeof(struct in_addr));
    } else if (af == AF_INET6) {
      lua_pushinteger(L, ntohs(sap->u.in6.sin6_port));
      lua_pushlstring(L, (char *) &sap->u.in6.sin6_addr,
       sizeof(struct in6_addr));
    } else
      return 0;
    return 2;
  } else {
    const int port = (int) lua_tointeger(L, 2);
    int in_len = SOCK_ADDR_LEN, af = AF_INET;
    const char *addr = lua_isnoneornil(L, 3) ? NULL
     : sock_checkladdr(L, 3, &in_len, &af);

    memset(sap, 0, sizeof(struct sock_addr));
    sap->u.addr.sa_family = (short) af;
    if (af == AF_INET) {
      sap->u.in.sin_port = htons((unsigned short) port);
      if (addr)
        memcpy(&sap->u.in.sin_addr, addr, in_len);
      sap->addrlen = sizeof(struct sockaddr_in);
    } else {
      sap->u.in6.sin6_port = htons((unsigned short) port);
      if (addr)
        memcpy(&sap->u.in6.sin6_addr, addr, in_len);
      sap->addrlen = sizeof(struct sockaddr_in6);
    }
    lua_settop(L, 1);
    return 1;
  };
}

/*
 * Arguments: sock_addr_udata, [path (string)]
 * Returns: sock_addr_udata | path (string)
 */
static int
sock_addr_file (lua_State *L)
{
  struct sock_addr *sap = checkudata(L, 1, SA_TYPENAME);

#ifndef _WIN32
  if (lua_gettop(L) == 1) {
    if (sap->u.addr.sa_family == AF_LOCAL) {
      lua_pushstring(L, sap->u.un.sun_path);
      return 1;
    }
  } else {
    size_t len;
    const char *path = luaL_checklstring(L, 2, &len);

    if (len < sizeof(sap->u.un.sun_path)) {
      sap->u.un.sun_family = AF_LOCAL;
      sap->addrlen = ++len;
      memcpy(sap->u.un.sun_path, path, len);

      lua_settop(L, 1);
      return 1;
    }
  };
#else
  (void) sap;
#endif
  return 0;
}

/*
 * Arguments: sock_addr_udata, sd_udata
 * Returns: [sock_addr_udata]
 */
static int
sock_addr_getsockname (lua_State *L)
{
  struct sock_addr *sap = checkudata(L, 1, SA_TYPENAME);
  sd_t sd = (sd_t) lua_unboxinteger(L, 2, SD_TYPENAME);

  sap->addrlen = SOCK_ADDR_LEN;
  if (!getsockname(sd, &sap->u.addr, &sap->addrlen)) {
    lua_settop(L, 1);
    return 1;
  }
  return sys_seterror(L, 0);
}

/*
 * Arguments: sock_addr_udata, sd_udata
 * Returns: [sock_addr_udata]
 */
static int
sock_addr_getpeername (lua_State *L)
{
  struct sock_addr *sap = checkudata(L, 1, SA_TYPENAME);
  sd_t sd = (sd_t) lua_unboxinteger(L, 2, SD_TYPENAME);

  sap->addrlen = SOCK_ADDR_LEN;
  if (!getpeername(sd, &sap->u.addr, &sap->addrlen)) {
    lua_settop(L, 1);
    return 1;
  }
  return sys_seterror(L, 0);
}

/*
 * Arguments: sock_addr_udata
 * Returns: string
 */
static int
sock_addr_tostring (lua_State *L)
{
  struct sock_addr *sap = checkudata(L, 1, SA_TYPENAME);

  lua_pushfstring(L, SA_TYPENAME " (%p)", sap);
  return 1;
}


#define ADDR_METHODS \
  {"getaddrinfo",	sock_getaddrinfo}, \
  {"getnameinfo",	sock_getnameinfo}, \
  {"getifaddrs",	sock_getifaddrs}, \
  {"inet_pton",		sock_inet_pton}, \
  {"inet_ntop",		sock_inet_ntop}, \
  {"addr",		sock_addr_new}

static luaL_Reg addr_meth[] = {
  {"inet",		sock_addr_inet},
  {"file",		sock_addr_file},
  {"getsockname",	sock_addr_getsockname},
  {"getpeername",	sock_addr_getpeername},
  {"__tostring",	sock_addr_tostring},
  {NULL, NULL}
};
Esempio n. 17
0
int lua_Animation_getClip(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 1:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA))
                {
                    Animation* instance = getInstance(state);
                    void* returnPtr = (void*)instance->getClip();
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = false;
                        luaL_getmetatable(state, "AnimationClip");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_Animation_getClip - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        case 2:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    (lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
                {
                    // Get parameter 1 off the stack.
                    const char* param1 = gameplay::ScriptUtil::getString(2, false);

                    Animation* instance = getInstance(state);
                    void* returnPtr = (void*)instance->getClip(param1);
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = false;
                        luaL_getmetatable(state, "AnimationClip");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    lua_type(state, 2) == LUA_TNUMBER)
                {
                    // Get parameter 1 off the stack.
                    unsigned int param1 = (unsigned int)luaL_checkunsigned(state, 2);

                    Animation* instance = getInstance(state);
                    void* returnPtr = (void*)instance->getClip(param1);
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = false;
                        luaL_getmetatable(state, "AnimationClip");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_Animation_getClip - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 1 or 2).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Esempio n. 18
0
int lua_Ray__init(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 0:
        {
            void* returnPtr = (void*)new Ray();
            if (returnPtr)
            {
                gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                object->instance = returnPtr;
                object->owns = true;
                luaL_getmetatable(state, "Ray");
                lua_setmetatable(state, -2);
            }
            else
            {
                lua_pushnil(state);
            }

            return 1;
            break;
        }
        case 1:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TNIL))
                {
                    // Get parameter 1 off the stack.
                    bool param1Valid;
                    gameplay::ScriptUtil::LuaArray<Ray> param1 = gameplay::ScriptUtil::getObjectPointer<Ray>(1, "Ray", true, &param1Valid);
                    if (!param1Valid)
                        break;

                    void* returnPtr = (void*)new Ray(*param1);
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = true;
                        luaL_getmetatable(state, "Ray");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_Ray__init - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        case 2:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TNIL) &&
                    (lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL))
                {
                    // Get parameter 1 off the stack.
                    bool param1Valid;
                    gameplay::ScriptUtil::LuaArray<Vector3> param1 = gameplay::ScriptUtil::getObjectPointer<Vector3>(1, "Vector3", true, &param1Valid);
                    if (!param1Valid)
                        break;

                    // Get parameter 2 off the stack.
                    bool param2Valid;
                    gameplay::ScriptUtil::LuaArray<Vector3> param2 = gameplay::ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true, &param2Valid);
                    if (!param2Valid)
                        break;

                    void* returnPtr = (void*)new Ray(*param1, *param2);
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = true;
                        luaL_getmetatable(state, "Ray");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_Ray__init - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        case 6:
        {
            do
            {
                if (lua_type(state, 1) == LUA_TNUMBER &&
                    lua_type(state, 2) == LUA_TNUMBER &&
                    lua_type(state, 3) == LUA_TNUMBER &&
                    lua_type(state, 4) == LUA_TNUMBER &&
                    lua_type(state, 5) == LUA_TNUMBER &&
                    lua_type(state, 6) == LUA_TNUMBER)
                {
                    // Get parameter 1 off the stack.
                    float param1 = (float)luaL_checknumber(state, 1);

                    // Get parameter 2 off the stack.
                    float param2 = (float)luaL_checknumber(state, 2);

                    // Get parameter 3 off the stack.
                    float param3 = (float)luaL_checknumber(state, 3);

                    // Get parameter 4 off the stack.
                    float param4 = (float)luaL_checknumber(state, 4);

                    // Get parameter 5 off the stack.
                    float param5 = (float)luaL_checknumber(state, 5);

                    // Get parameter 6 off the stack.
                    float param6 = (float)luaL_checknumber(state, 6);

                    void* returnPtr = (void*)new Ray(param1, param2, param3, param4, param5, param6);
                    if (returnPtr)
                    {
                        gameplay::ScriptUtil::LuaObject* object = (gameplay::ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(gameplay::ScriptUtil::LuaObject));
                        object->instance = returnPtr;
                        object->owns = true;
                        luaL_getmetatable(state, "Ray");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_Ray__init - Failed to match the given parameters to a valid function signature.");
            lua_error(state);
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 0, 1, 2 or 6).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Esempio n. 19
0
LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) {
  luaL_getmetatable(L, tname);
  lua_setmetatable(L, -2);
}
Esempio n. 20
0
static chan_pushqueue(lua_State* L, struct queue_t* q)
{
    lua_pushlightuserdata(L, q);
    luaL_getmetatable(L, METATABLE_NAME);
    lua_setmetatable(L, -2);
}
Esempio n. 21
0
// minetest.get_mapgen_object(objectname)
// returns the requested object used during map generation
int ModApiMapgen::l_get_mapgen_object(lua_State *L)
{
	const char *mgobjstr = lua_tostring(L, 1);

	int mgobjint;
	if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : ""))
		return 0;

	enum MapgenObject mgobj = (MapgenObject)mgobjint;

	EmergeManager *emerge = getServer(L)->getEmergeManager();
	Mapgen *mg = emerge->getCurrentMapgen();
	if (!mg)
		return 0;

	size_t maplen = mg->csize.X * mg->csize.Z;

	switch (mgobj) {
		case MGOBJ_VMANIP: {
			ManualMapVoxelManipulator *vm = mg->vm;

			// VoxelManip object
			LuaVoxelManip *o = new LuaVoxelManip(vm, true);
			*(void **)(lua_newuserdata(L, sizeof(void *))) = o;
			luaL_getmetatable(L, "VoxelManip");
			lua_setmetatable(L, -2);

			// emerged min pos
			push_v3s16(L, vm->m_area.MinEdge);

			// emerged max pos
			push_v3s16(L, vm->m_area.MaxEdge);

			return 3; }
		case MGOBJ_HEIGHTMAP: {
			if (!mg->heightmap)
				return 0;

			lua_newtable(L);
			for (size_t i = 0; i != maplen; i++) {
				lua_pushinteger(L, mg->heightmap[i]);
				lua_rawseti(L, -2, i + 1);
			}

			return 1; }
		case MGOBJ_BIOMEMAP: {
			if (!mg->biomemap)
				return 0;

			lua_newtable(L);
			for (size_t i = 0; i != maplen; i++) {
				lua_pushinteger(L, mg->biomemap[i]);
				lua_rawseti(L, -2, i + 1);
			}

			return 1; }
		case MGOBJ_HEATMAP: { // Mapgen V7 specific objects
		case MGOBJ_HUMIDMAP:
			if (strcmp(emerge->params.mg_name.c_str(), "v7"))
				return 0;

			MapgenV7 *mgv7 = (MapgenV7 *)mg;

			float *arr = (mgobj == MGOBJ_HEATMAP) ?
				mgv7->noise_heat->result : mgv7->noise_humidity->result;
			if (!arr)
				return 0;

			lua_newtable(L);
			for (size_t i = 0; i != maplen; i++) {
				lua_pushnumber(L, arr[i]);
				lua_rawseti(L, -2, i + 1);
			}

			return 1; }
		case MGOBJ_GENNOTIFY: {
			lua_newtable(L);
			for (int i = 0; flagdesc_gennotify[i].name; i++) {
				if (!(emerge->gennotify & flagdesc_gennotify[i].flag))
					continue;

				std::vector<v3s16> *posvec = mg->gen_notifications[i];
				if (!posvec)
					return 0;

				lua_newtable(L);
				for (unsigned int j = 0; j != posvec->size(); j++) {
					push_v3s16(L, (*posvec)[j]);
					lua_rawseti(L, -2, j + 1);
				}
				lua_setfield(L, -2, flagdesc_gennotify[i].name);

				posvec->clear();
			}

			return 1; }
	}

	return 0;
}
Esempio n. 22
0
/*
 * connection = DBD.PostgreSQL.New(dbname, user, password, host, port)
 */
static int connection_new(lua_State *L) {
    int n = lua_gettop(L);
    connection_t *conn = NULL;

    const char *host = NULL;
    const char *user = NULL;
    const char *password = NULL;
    const char *db = NULL;
    const char *port = NULL;

    const char *options = NULL; /* TODO always NULL */
    const char *tty = NULL; /* TODO always NULL */

    char portbuf[18];

    /* db, user, password, host, port */
    switch (n) {
    case 5:
	if (lua_isnil(L, 5) == 0) 
	{
	    int pport = luaL_checkint(L, 5);

	    if (pport >= 1 && pport <= 65535) {
		snprintf(portbuf, sizeof(portbuf), "%d", pport);
		port = portbuf;
	    } else {
		luaL_error(L, DBI_ERR_INVALID_PORT, pport);
	    }
	}
    case 4: 
	if (lua_isnil(L, 4) == 0) 
	    host = luaL_checkstring(L, 4);
    case 3:
	if (lua_isnil(L, 3) == 0) 
	    password = luaL_checkstring(L, 3);
    case 2:
	if (lua_isnil(L, 2) == 0) 
	    user = luaL_checkstring(L, 2);
    case 1:
	/*
	 * db is the only mandatory parameter
	 */
	db = luaL_checkstring(L, 1);
    }

    conn = (connection_t *)lua_newuserdata(L, sizeof(connection_t));

    conn->postgresql = PQsetdbLogin(host, port, options, tty, db, user, password);
    conn->statement_id = 0;
    conn->autocommit = 0;
    begin(conn);

    if (PQstatus(conn->postgresql) != CONNECTION_OK) {
	lua_pushnil(L);
	lua_pushfstring(L, DBI_ERR_CONNECTION_FAILED, PQerrorMessage(conn->postgresql));
	return 2;
    }

    luaL_getmetatable(L, DBD_POSTGRESQL_CONNECTION);
    lua_setmetatable(L, -2);

    return 1;
}
Esempio n. 23
0
/*
** Define the metatable for the object on top of the stack
*/
LUASQL_API void luasql_setmeta (lua_State *L, const char *name) {
	luaL_getmetatable (L, name);
	lua_setmetatable (L, -2);
}
Esempio n. 24
0
int lua_ThemeUVs__init(lua_State* state)
{
    // Get the number of parameters.
    int paramCount = lua_gettop(state);

    // Attempt to match the parameters to a valid binding.
    switch (paramCount)
    {
        case 0:
        {
            void* returnPtr = (void*)new Theme::UVs();
            if (returnPtr)
            {
                ScriptUtil::LuaObject* object = (ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(ScriptUtil::LuaObject));
                object->instance = returnPtr;
                object->owns = true;
                luaL_getmetatable(state, "ThemeUVs");
                lua_setmetatable(state, -2);
            }
            else
            {
                lua_pushnil(state);
            }

            return 1;
            break;
        }
        case 4:
        {
            if (lua_type(state, 1) == LUA_TNUMBER &&
                lua_type(state, 2) == LUA_TNUMBER &&
                lua_type(state, 3) == LUA_TNUMBER &&
                lua_type(state, 4) == LUA_TNUMBER)
            {
                // Get parameter 1 off the stack.
                float param1 = (float)luaL_checknumber(state, 1);

                // Get parameter 2 off the stack.
                float param2 = (float)luaL_checknumber(state, 2);

                // Get parameter 3 off the stack.
                float param3 = (float)luaL_checknumber(state, 3);

                // Get parameter 4 off the stack.
                float param4 = (float)luaL_checknumber(state, 4);

                void* returnPtr = (void*)new Theme::UVs(param1, param2, param3, param4);
                if (returnPtr)
                {
                    ScriptUtil::LuaObject* object = (ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(ScriptUtil::LuaObject));
                    object->instance = returnPtr;
                    object->owns = true;
                    luaL_getmetatable(state, "ThemeUVs");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }
            else
            {
                lua_pushstring(state, "lua_ThemeUVs__init - Failed to match the given parameters to a valid function signature.");
                lua_error(state);
            }
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 0 or 4).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Esempio n. 25
0
int mumble_connect(lua_State *l)
{
	const char* server_host_str = luaL_checkstring(l, 1);
	int port = luaL_checkinteger(l, 2);

	const char* certificate_file = luaL_checkstring(l, 3);
	const char* key_file = luaL_checkstring(l, 4);

	MumbleClient *client = lua_newuserdata(l, sizeof(MumbleClient));
	luaL_getmetatable(l, METATABLE_CLIENT);
	lua_setmetatable(l, -2);

	lua_rawgeti(l, LUA_REGISTRYINDEX, MUMBLE_CONNECTIONS);
	lua_pushvalue(l, -2);

	client->self = luaL_ref(l, -2);
	lua_pop(l, 1);

	client->l = l;

	lua_newtable(l);
	client->hooks = luaL_ref(l, LUA_REGISTRYINDEX);

	lua_newtable(l);
	client->users = luaL_ref(l, LUA_REGISTRYINDEX);

	lua_newtable(l);
	client->channels = luaL_ref(l, LUA_REGISTRYINDEX);

	client->host = server_host_str;
	client->port = port;
	client->nextping = gettime() + PING_TIMEOUT;
	client->time = gettime();
	client->volume = 1;
	client->audio_job = NULL;
	client->connected = true;
	client->synced = false;
	client->audio_finished = false;
	client->audio_target = 0;

	int err;
	client->encoder = opus_encoder_create(48000, 1, OPUS_APPLICATION_AUDIO, &err);

	if (err != OPUS_OK) {
		lua_pushnil(l);
		lua_pushfstring(l, "could not initialize encoder: %s", opus_strerror(err));
		return 2;
	}

	opus_encoder_ctl(client->encoder, OPUS_SET_VBR(0));
	opus_encoder_ctl(client->encoder, OPUS_SET_BITRATE(40000));

	client->socket = socket(AF_INET, SOCK_STREAM, 0);
	if (client->socket < 0) {
		lua_pushnil(l);
		lua_pushfstring(l, "could not create socket: %s", strerror(errno));
		return 2;
	}

	struct timeval timeout;
	timeout.tv_sec = 5;
	timeout.tv_usec = 0;

	if (setsockopt(client->socket, SOL_SOCKET, (SO_RCVTIMEO | SO_SNDTIMEO), (char *)&timeout, sizeof(timeout)) < 0) {
		lua_pushnil(l);
		lua_pushfstring(l, "setsockopt failed: %s", strerror(errno));
		return 2;
	}

	client->ssl_context = SSL_CTX_new(SSLv23_client_method());

	if (client->ssl_context == NULL) {
		lua_pushnil(l);
		lua_pushstring(l, "could not create SSL context");
		return 2;
	}

	if (certificate_file != NULL) {
		if (!SSL_CTX_use_certificate_chain_file(client->ssl_context, certificate_file) ||
			!SSL_CTX_use_PrivateKey_file(client->ssl_context, key_file, SSL_FILETYPE_PEM) ||
			!SSL_CTX_check_private_key(client->ssl_context)) {

			lua_pushnil(l);
			lua_pushstring(l, "could not load certificate and/or key file");
			return 2;
		}
	}

	struct hostent *server_host;
	struct sockaddr_in server_addr;

	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port);

	server_host = gethostbyname(server_host_str);
	if (server_host == NULL || server_host->h_addr_list[0] == NULL || server_host->h_addrtype != AF_INET) {
		lua_pushnil(l);
		lua_pushstring(l, "could not parse server address");
		return 2;
	}
	memmove(&server_addr.sin_addr, server_host->h_addr_list[0], server_host->h_length);

	if (connect(client->socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) != 0) {
		lua_pushnil(l);
		lua_pushfstring(l, "could not connect to server: %s", strerror(errno));
		return 2;
	}
	
	client->ssl = SSL_new(client->ssl_context);

	if (client->ssl == NULL) {
		lua_pushnil(l);
		lua_pushstring(l, "could not create SSL object");
		return 2;
	}

	if (SSL_set_fd(client->ssl, client->socket) == 0) {
		lua_pushnil(l);
		lua_pushstring(l, "could not set SSL file descriptor");
		return 2;
	}

	if (err = SSL_connect(client->ssl) != 1) {
		lua_pushnil(l);
		lua_pushfstring(l, "could not create secure connection: %s", SSL_get_error(client->ssl, err));
		return 2;
	}

	// Non blocking after connect
	int flags = fcntl(client->socket, F_GETFL, 0);
	fcntl(client->socket, F_SETFL, flags | O_NONBLOCK);

	if (pthread_mutex_init(&client->lock , NULL)) {
		lua_pushnil(l);
		lua_pushstring(l, "could not init mutex");
		return 2;
	}

	if (pthread_cond_init(&client->cond, NULL)) {
		lua_pushnil(l);
		lua_pushstring(l, "could not init condition");
		return 2;
	}

	if (pthread_create(&client->audio_thread, NULL, (void*) mumble_audiothread, client)){
		lua_pushnil(l);
		lua_pushstring(l, "could not create audio thread");
		return 2;
	}

	return 1;
}
Esempio n. 26
0
void lutok::state::get_metatable(const std::string& name){
	luaL_getmetatable(_pimpl->lua_state, name.c_str());
}
Esempio n. 27
0
void addon_pload_data_push(lua_State *L) {
	lua_newuserdata(L, sizeof(struct addon_pload_data));
	luaL_getmetatable(L, ADDON_PLOAD_DATA_METATABLE);
	lua_setmetatable(L, -2);
}
Esempio n. 28
0
LUA_API void lua_pushmatrix (lua_State *L, lua_matrix3x4_t &matrix) {
  lua_matrix3x4_t *pMat = (lua_matrix3x4_t *)lua_newuserdata(L, sizeof(lua_matrix3x4_t));
  *pMat = matrix;
  luaL_getmetatable(L, "matrix3x4_t");
  lua_setmetatable(L, -2);
}
Esempio n. 29
0
File: bind.c Progetto: BeanGu/LuCI
/**
 * connect()/bind() shortcut
 */
static int nixio__bind_connect(lua_State *L, int do_bind) {
	const char *host = NULL;
	if (!lua_isnoneornil(L, 1)) {
		host = luaL_checklstring(L, 1, NULL);
	}
	const char *port = luaL_checklstring(L, 2, NULL);
	const char *family = luaL_optlstring(L, 3, "any", NULL);
	const char *socktype = luaL_optlstring(L, 4, "stream", NULL);

	struct addrinfo hints, *result, *rp;
	memset(&hints, 0, sizeof(hints));

	if (!strcmp(family, "any")) {
		hints.ai_family = AF_UNSPEC;
	} else if (!strcmp(family, "inet")) {
		hints.ai_family = AF_INET;
	} else if (!strcmp(family, "inet6")) {
		hints.ai_family = AF_INET6;
	} else {
		return luaL_argerror(L, 3, "supported values: any, inet, inet6");
	}

	if (!strcmp(socktype, "any")) {
		hints.ai_socktype = 0;
	} else if (!strcmp(socktype, "stream")) {
		hints.ai_socktype = SOCK_STREAM;
	} else if (!strcmp(socktype, "dgram")) {
		hints.ai_socktype = SOCK_DGRAM;
	} else {
		return luaL_argerror(L, 4, "supported values: any, stream, dgram");
	}

	if (do_bind) {
		hints.ai_flags |= AI_PASSIVE;
	}

	hints.ai_protocol = 0;

	int aistat = getaddrinfo(host, port, &hints, &result);
	if (aistat) {
		lua_pushnil(L);
		lua_pushinteger(L, aistat);
		lua_pushstring(L, gai_strerror(aistat));
		return 3;
	}

	/* create socket object */
	nixio_sock *sock = lua_newuserdata(L, sizeof(nixio_sock));
	int status = -1, clstat;

	for (rp = result; rp != NULL; rp = rp->ai_next) {
		sock->fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
		if (sock->fd == -1) {
			continue;
		}

		if (do_bind) {
			int one = 1;
			setsockopt(sock->fd, SOL_SOCKET, SO_REUSEADDR,
			 (char*)&one, sizeof(one));
			status = bind(sock->fd, rp->ai_addr, rp->ai_addrlen);
		} else {
			do {
				status = connect(sock->fd, rp->ai_addr, rp->ai_addrlen);
			} while (status == -1 && errno == EINTR);
		}

		/* on success */
		if (!status) {
			sock->domain = rp->ai_family;
			sock->type = rp->ai_socktype;
			sock->protocol = rp->ai_protocol;
			break;
		}

		do {
#ifndef __WINNT__
			clstat = close(sock->fd);
#else
			clstat = closesocket(sock->fd);
#endif
		} while (clstat == -1 && errno == EINTR);
	}

	freeaddrinfo(result);

	/* on failure */
	if (status) {
		return nixio__perror_s(L);
	}

	luaL_getmetatable(L, NIXIO_META);
	lua_setmetatable(L, -2);

	return 1;
}
Esempio n. 30
0
static int lua_new_packet(lua_State *L,int packettype){
	int argtype = lua_type(L,1); 
	if(packettype == WPACKET){
		if(argtype == LUA_TNUMBER || argtype == LUA_TNIL || argtype == LUA_TNONE){
			//参数为数字,构造一个初始大小为len的wpacket
			size_t len = 0;
			if(argtype == LUA_TNUMBER) len = size_of_pow2(lua_tointeger(L,1));
			if(len < 64) len = 64;
			lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p));
			luaL_getmetatable(L, LUAPACKET_METATABLE);
			lua_setmetatable(L, -2);
			p->_packet = (packet_t)wpk_create(len);
			return 1;			
		}else if(argtype == LUA_TSTRING){
			size_t len;
			char *data = (char*)lua_tolstring(L,1,&len);
			lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p));
			luaL_getmetatable(L, LUAPACKET_METATABLE);
			lua_setmetatable(L, -2);
			p->_packet = (packet_t)wpk_create_by_bin((int8_t*)data,len);
			return 1;				
		}else if(argtype ==  LUA_TUSERDATA){
			lua_packet_t other = lua_getluapacket(L,1);
			if(!other)
				return luaL_error(L,"invaild opration for arg1");
			if(other->_packet->type == RAWPACKET)
				return luaL_error(L,"invaild opration for arg1");
			lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p));
			luaL_getmetatable(L, LUAPACKET_METATABLE);
			lua_setmetatable(L, -2);
			p->_packet = make_writepacket(other->_packet);//(packet_t)wpk_copy_create(other->_packet);
			return 1;												
		}else if(argtype == LUA_TTABLE){
			wpacket_t wpk = wpk_create(512);
			if(0 != lua_pack_table(wpk,L,-1)){
				destroy_packet((packet_t)wpk);
				return luaL_error(L,"table should not hava metatable");	
				//lua_pushnil(L);
			}else{
				lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p));
				luaL_getmetatable(L, LUAPACKET_METATABLE);
				lua_setmetatable(L, -2);
				p->_packet = (packet_t)wpk;		
			}
			return 1;
		}
		else	
			return luaL_error(L,"invaild opration for arg1");		
	}else if(packettype == RAWPACKET){
		if(argtype == LUA_TSTRING){
			//参数为string,构造一个函数数据data的rawpacket
			size_t len;
			char *data = (char*)lua_tolstring(L,1,&len);
			lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p));
			luaL_getmetatable(L, LUAPACKET_METATABLE);
			lua_setmetatable(L, -2);				
			p->_packet = (packet_t)rawpacket_create2(data,len);
			return 1;
		}else if(argtype ==  LUA_TUSERDATA){
			lua_packet_t other = lua_getluapacket(L,1);
			if(!other)
				return luaL_error(L,"invaild opration for arg1");
			if(other->_packet->type != RAWPACKET)
				return luaL_error(L,"invaild opration for arg1");
			lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p));
			luaL_getmetatable(L, LUAPACKET_METATABLE);
			lua_setmetatable(L, -2);
			p->_packet = clone_packet(other->_packet);
			return 1;							
		}else
			return luaL_error(L,"invaild opration for arg1");
	}else if(packettype == RPACKET){
		if(argtype ==  LUA_TUSERDATA){
			lua_packet_t other = lua_getluapacket(L,1);
			if(!other)
				return luaL_error(L,"invaild opration for arg1");
			if(other->_packet->type == RAWPACKET)
				return luaL_error(L,"invaild opration for arg1");
			lua_packet_t p = (lua_packet_t)lua_newuserdata(L, sizeof(*p));
			luaL_getmetatable(L, LUAPACKET_METATABLE);
			lua_setmetatable(L, -2);
			p->_packet = make_readpacket(other->_packet);
			return 1;					
		}else
			return luaL_error(L,"invaild opration for arg1");	
	}else
		return luaL_error(L,"invaild packet type");
}