Пример #1
0
const char *lgi_sd (lua_State *L)
{
  int i;
  static gchar *msg = 0;
  g_free (msg);
  msg = g_strdup ("");
  int top = lua_gettop (L);
  for (i = 1; i <= top; i++)
    {
      int t = lua_type (L, i);
      gchar *item, *nmsg;
      switch (t)
	{
	case LUA_TSTRING:
	  item = g_strdup_printf ("`%s'", lua_tostring (L, i));
	  break;

	case LUA_TBOOLEAN:
	  item = g_strdup_printf (lua_toboolean (L, i) ? "true" : "false");
	  break;

	case LUA_TNUMBER:
	  item = g_strdup_printf ("%g", lua_tonumber (L, i));
	  break;

	default:
	  item = g_strdup_printf ("%s(%p)", lua_typename (L, t),
				  lua_topointer (L, i));
	  break;
	}
      nmsg = g_strconcat (msg, " ", item, NULL);
      g_free (msg);
      g_free (item);
      msg = nmsg;
    }
  return msg;
}
Пример #2
0
/**
 * @param: the value (at stack -2)
 * @param: the cycle table (at stack -1)
 * @return: the string
 */
static int l_pretty_repr_slice(lua_State *L)
{
    int type = lua_type(L, -2);
    switch (type) {
    case LUA_TSTRING: 
        lua_pop(L, 1);
        l_repr_string(L);
        break;
    case LUA_TTABLE: 
        lua_pushcfunction(L, l_pretty_repr_table);
        lua_pushvalue(L, -3);	/* the table and cycle table are copied */
        lua_pushvalue(L, -3);
        lua_call(L, 2, 1);
        break;
    case LUA_TNIL: 
    case LUA_TNUMBER: 
    case LUA_TBOOLEAN: 
        lua_pop(L, 1);
        lua_getglobal(L, "tostring");
        lua_insert(L, -2);
        lua_call(L, 1, 1);
        break;
    case LUA_TFUNCTION: 
    case LUA_TUSERDATA: 
    case LUA_TTHREAD: 
    case LUA_TLIGHTUSERDATA: 
        lua_pop(L, 1);
        const void *p;
        p = lua_topointer(L, -1);
        lua_pushfstring(L, "%s_(%p)", lua_typename(L, type), p);
        break;
    default:
        lua_pushfstring(L, "unknown_(%d)", type);
        break;
    }
    return 1;
}
Пример #3
0
int lua_cbacks::field(lua_State *ls) 
{
	lua_getglobal(ls, "sievt");
	sinsp_evt* evt = (sinsp_evt*)lua_touserdata(ls, -1);
	lua_pop(ls, 1);

	if(evt == NULL)
	{
		string err = "invalid call to evt.field()";
		fprintf(stderr, "%s\n", err.c_str());
		throw sinsp_exception("chisel error");
	}

	sinsp_filter_check* chk = (sinsp_filter_check*)lua_topointer(ls, 1);
	if(chk == NULL)
	{
		//
		// This happens if the lua code is calling field() without invoking 
		// sysdig.request_field() before. 
		//
		lua_pushnil(ls);
		return 1;
	}

	uint32_t vlen;
	uint8_t* rawval = chk->extract(evt, &vlen);

	if(rawval != NULL)
	{
		return rawval_to_lua_stack(ls, rawval, chk->get_field_info(), vlen);
	}
	else
	{
		lua_pushnil(ls);
		return 1;
	}
}
/**
 * Find code chunk associated with the given key in code cache,
 * and push it to the top of Lua stack if found.
 *
 * Stack layout before call:
 *         |     ...    | <- top
 *
 * Stack layout after call:
 *         | code chunk | <- top
 *         |     ...    |
 *
 * */
static ngx_int_t
ngx_http_lua_cache_load_code(lua_State *L, const char *key)
{
    /*  get code cache table */
    lua_pushlightuserdata(L, &ngx_http_lua_code_cache_key);
    lua_rawget(L, LUA_REGISTRYINDEX);    /*  sp++ */

    dd("Code cache table to load: %p", lua_topointer(L, -1));

    if (!lua_istable(L, -1)) {
        dd("Error: code cache table to load did not exist!!");
        return NGX_ERROR;
    }

    lua_getfield(L, -1, key);    /*  sp++ */

    if (lua_isfunction(L, -1)) {
        /*  call closure factory to gen new closure */
        int rc = lua_pcall(L, 0, 1, 0);

        if (rc == 0) {
            /*  remove cache table from stack, leave code chunk at
             *  top of stack */
            lua_remove(L, -2);   /*  sp-- */
            return NGX_OK;
        }
    }

    dd("Value associated with given key in code cache table is not code "
            "chunk: stack top=%d, top value type=%s\n",
            lua_gettop(L), lua_typename(L, -1));

    /*  remove cache table and value from stack */
    lua_pop(L, 2);                                /*  sp-=2 */

    return NGX_DECLINED;
}
Пример #5
0
Файл: lauxlib.c Проект: lua/lua
LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
  if (luaL_callmeta(L, idx, "__tostring")) {  /* metafield? */
    if (!lua_isstring(L, -1))
      luaL_error(L, "'__tostring' must return a string");
  }
  else {
    switch (lua_type(L, idx)) {
      case LUA_TNUMBER: {
        if (lua_isinteger(L, idx))
          lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx));
        else
          lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx));
        break;
      }
      case LUA_TSTRING:
        lua_pushvalue(L, idx);
        break;
      case LUA_TBOOLEAN:
        lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
        break;
      case LUA_TNIL:
        lua_pushliteral(L, "nil");
        break;
      default: {
        int tt = luaL_getmetafield(L, idx, "__name");  /* try name */
        const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) :
                                                 luaL_typename(L, idx);
        lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx));
        if (tt != LUA_TNIL)
          lua_remove(L, -2);  /* remove '__name' */
        break;
      }
    }
  }
  return lua_tolstring(L, -1, len);
}
Пример #6
0
/**
 * @brief Copies the full userdata on the top of src to the top of dst.
 *
 * If the userdata has a metatable, the metatable is also copied.
 *
 * @param src source state
 * @param dst destination state
 */
static void sglua_copy_userdata(lua_State* src, lua_State* dst) {

  int indent = lua_gettop(dst) * 6  + 2;

  /* copy the data */
                                  /* src: ... udata
                                     dst: ... */
  size_t size = lua_objlen(src, -1);
  void* src_block = lua_touserdata(src, -1);
  void* dst_block = lua_newuserdata(dst, size);
                                  /* dst: ... udata */
  memcpy(dst_block, src_block, size);

  /* copy the metatable if any */
  int has_meta_table = lua_getmetatable(src, -1);
                                  /* src: ... udata mt? */
  if (has_meta_table) {
    XBT_DEBUG("%sCopying metatable of userdata (%p)",
        sglua_get_spaces(indent), lua_topointer(src, -1));
                                  /* src: ... udata mt */
    sglua_copy_table(src, dst);
                                  /* src: ... udata mt
                                     dst: ... udata mt */
    lua_pop(src, 1);
                                  /* src: ... udata */
    lua_setmetatable(dst, -2);
                                  /* dst: ... udata */

    XBT_DEBUG("%sMetatable of userdata copied", sglua_get_spaces(indent));
  }
  else {
    XBT_DEBUG("%sNo metatable for this userdata",
        sglua_get_spaces(indent));
                                  /* src: ... udata */
  }
}
Пример #7
0
/*
 * Core function to fetch message information (flags, date, size).
 */
static int
ifcore_fetchfast(lua_State *lua)
{
	int r;
	char *flags, *date, *size;

	flags = date = size = NULL;

	if (lua_gettop(lua) != 2)
		luaL_error(lua, "wrong number of arguments");
	luaL_checktype(lua, 1, LUA_TLIGHTUSERDATA);
	luaL_checktype(lua, 2, LUA_TSTRING);

	while ((r = request_fetchfast((session *)(lua_topointer(lua, 1)),
	    lua_tostring(lua, 2), &flags, &date, &size)) == STATUS_NONE);

	lua_pop(lua, 2);

	if (r == -1)
		return 0;

	lua_pushboolean(lua, (r == STATUS_OK));

	if (!flags || !date || !size)
		return 1;

	lua_pushstring(lua, flags);
	lua_pushstring(lua, date);
	lua_pushstring(lua, size);

	xfree(flags);
	xfree(date);
	xfree(size);

	return 4;
}
Пример #8
0
/*
 * Core function to list available mailboxes.
 */
static int
ifcore_list(lua_State *lua)
{
	int r;
	char *mboxs, *folders;

	mboxs = folders = NULL;

	if (lua_gettop(lua) != 3)
		luaL_error(lua, "wrong number of arguments");
	luaL_checktype(lua, 1, LUA_TLIGHTUSERDATA);
	luaL_checktype(lua, 2, LUA_TSTRING);
	luaL_checktype(lua, 3, LUA_TSTRING);

	while ((r = request_list((session *)(lua_topointer(lua, 1)),
	    lua_tostring(lua, 2), lua_tostring(lua, 3), &mboxs, &folders)) ==
	    STATUS_NONE);

	lua_pop(lua, 3);

	if (r == -1)
		return 0;

	lua_pushboolean(lua, (r == STATUS_OK));

	if (!mboxs && !folders)
		return 1;

	lua_pushstring(lua, mboxs);
	lua_pushstring(lua, folders);

	xfree(mboxs);
	xfree(folders);

	return 3;
}
Пример #9
0
/**
 * \brief Registers a menu into a context (table or a userdata).
 *
 * This function can be called safely even while iterating on the menus list.
 *
 * \param menu_ref Lua ref of the menu to add.
 * \param context_index Index of the table or userdata in the stack.
 * \param on_top \c true to place this menu on top of existing one in the
 * same context, \c false to place it behind.
 */
void LuaContext::add_menu(
    const ScopedLuaRef& menu_ref,
    int context_index,
    bool on_top
) {
  const void* context;
  if (lua_type(l, context_index) == LUA_TUSERDATA) {
    ExportableToLuaPtr* userdata = static_cast<ExportableToLuaPtr*>(
        lua_touserdata(l, context_index));
    context = userdata->get();
  }
  else {
    context = lua_topointer(l, context_index);
  }

  if (on_top) {
    menus.emplace_back(menu_ref, context);
  }
  else {
    menus.emplace_front(menu_ref, context);
  }

  menu_on_started(menu_ref);
}
Пример #10
0
static int luaB_tostring (lua_State *L)
{
	luaL_checkany(L, 1);
	if (luaL_callmeta(L, 1, "__tostring"))  /* is there a metafield? */
		return 1;  /* use its value */
	switch (lua_type(L, 1)) {
	case LUA_TNUMBER:
		lua_pushstring(L, lua_tostring(L, 1));
		break;
	case LUA_TSTRING:
		lua_pushvalue(L, 1);
		break;
	case LUA_TBOOLEAN:
		lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false"));
		break;
	case LUA_TNIL:
		lua_pushliteral(L, "nil");
		break;
	default:
		lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1));
		break;
	}
	return 1;
}
Пример #11
0
/* a simple "print". based on the code in lbaselib.c */
static int print(lua_State* inState)
{
	int n = lua_gettop(inState);
	int i;
	string theString;
	
	for (i=1; i<=n; i++)
	{
		if (i>1) theString = "\t";
		if (lua_isstring(inState, i))
			theString += string(lua_tostring(inState, i));
		else
		{
			char theBuffer[512];
			sprintf(theBuffer, "%s:%p",lua_typename(inState, lua_type(inState, i)),lua_topointer(inState,i));
			theString += string(theBuffer);
		}
	}
	//theString += string("\n");
	
	UTIL_ClientPrintAll(HUD_PRINTNOTIFY, theString.c_str());
	
	return 0;
}
Пример #12
0
static int B_SceneObject_getControlInfo(lua_State* L)
{
	SceneObject* pSO=*(SceneObject**)lua_topointer(L,-1);
	lua_newtable(L);
	lua_pushstring(L,"up");
	lua_pushnumber(L,pSO->m_CI.up);
	lua_settable(L,-3);
	lua_pushstring(L,"down");
	lua_pushnumber(L,pSO->m_CI.down);
	lua_settable(L,-3);
	lua_pushstring(L,"left");
	lua_pushnumber(L,pSO->m_CI.left);
	lua_settable(L,-3);
	lua_pushstring(L,"right");
	lua_pushnumber(L,pSO->m_CI.right);
	lua_settable(L,-3);
	lua_pushstring(L,"space");
	lua_pushnumber(L,pSO->m_CI.space);
	lua_settable(L,-3);
	lua_pushstring(L,"ctrl");
	lua_pushnumber(L,pSO->m_CI.ctrl);
	lua_settable(L,-3);
	return 1;
}
Пример #13
0
LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len)
{
    if (!luaL_callmeta(L, idx, "__tostring"))    /* no metafield? */
    {
        switch (lua_type(L, idx))
        {
        case LUA_TNUMBER:
        case LUA_TSTRING:
            lua_pushvalue(L, idx);
            break;
        case LUA_TBOOLEAN:
            lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false"));
            break;
        case LUA_TNIL:
            lua_pushliteral(L, "nil");
            break;
        default:
            lua_pushfstring(L, "%s: %p", luaL_typename(L, idx),
                            lua_topointer(L, idx));
            break;
        }
    }
    return lua_tolstring(L, -1, len);
}
Пример #14
0
int thl_crep(lua_State *L) {
	
	int i = lua_isstring(L, -1);  // make sure it's a string...
	if (i != 1) 
		return 4;
	const void * ptr = lua_tostring(L, -1);
	char * tptr = (char *) ptr;
	void * IPptr;				
	lua_pushstring(L, "lua_dfsanchor");  /* push key */
    lua_gettable(L, LUA_REGISTRYINDEX);  /* retrieve value */

	_anchor * anch = (_anchor *) lua_topointer(L, -1);
	//Process * proc = (Process *) anch -> reserved;
	
	int len = strlen(tptr);
	++len;                          // it's a string, so leave room for terminating null!
	int value = dfscrep(* anch, &IPptr, len, "A");  

	strcpy((char *) IPptr , tptr);

	lua_pushnumber(L, value);
	lua_pushlightuserdata(L, (void *) IPptr);
	return 2;
}
Пример #15
0
static int luaClientPrint(lua_State *L) {
    // No output client set? => Discard
    if (!output_client || !CLIENT_USED(output_client)) 
        return 0;

    int n=lua_gettop(L);
    for (int i=1; i <= n; i++) {
        if (i > 1) server_writeto(output_client, "\t", 1);
        if (lua_isstring(L,i))
            server_writeto(output_client, lua_tostring(L,i), lua_strlen(L, i));
        else if (lua_isnil(L,i))
            server_writeto(output_client, "nil", 3);
        else if (lua_isboolean(L,i))
            lua_toboolean(L,i) ? server_writeto(output_client, "true",  4): 
                                 server_writeto(output_client, "false", 5);
        else {
            char buffer[128];
            snprintf(buffer, sizeof(buffer), "%s:%p", lua_typename(L,lua_type(L,i)), lua_topointer(L,i));
            server_writeto(output_client, buffer, strlen(buffer));
        }
    }
    server_writeto(output_client, "\r\n", 2);
    return 0;
}
Пример #16
0
/** Look for an item: table, function, etc.
 * \param L The Lua VM state.
 * \param item The pointer item.
 */
bool
luaA_hasitem(lua_State *L, const void *item)
{
    lua_pushnil(L);
    while(luaA_next(L, -2))
    {
        if(lua_topointer(L, -1) == item)
        {
            /* remove value and key */
            lua_pop(L, 2);
            return true;
        }
        if(lua_istable(L, -1))
            if(luaA_hasitem(L, item))
            {
                /* remove key and value */
                lua_pop(L, 2);
                return true;
            }
        /* remove value */
        lua_pop(L, 1);
    }
    return false;
}
Пример #17
0
/**
 * \brief Calls the on_command_released() method of the menus associated to a context.
 * \param context_index Index of an object with menus.
 * \param command The game command just released.
 * \return \c true if the event was handled and should stop being propagated.
 */
bool LuaContext::menus_on_command_released(int context_index,
    GameCommand command) {

  const void* context;
  if (lua_type(l, context_index) == LUA_TUSERDATA) {
    ExportableToLuaPtr* userdata = static_cast<ExportableToLuaPtr*>(
        lua_touserdata(l, context_index));
    context = userdata->get();
  }
  else {
    context = lua_topointer(l, context_index);
  }

  bool handled = false;
  std::list<LuaMenuData>::reverse_iterator it;
  for (it = menus.rbegin(); it != menus.rend() && !handled; ++it) {
    const ScopedLuaRef& menu_ref = it->ref;
    if (it->context == context) {
      handled = menu_on_command_released(menu_ref, command);
    }
  }

  return handled;
}
Пример #18
0
int NL_dofile(lua_State *state)
{
    lua_getglobal( state, ONS_LUA_HANDLER_PTR );
    LUAHandler *lh = (LUAHandler*)lua_topointer( state, -1 );

    const char *str = luaL_checkstring( state, 1 );

    unsigned long length = lh->sh->cBR->getFileLength(str);
    if (length == 0) {
        printf("cannot open %s\n", str);
        return 0;
    }

    unsigned char *buffer = new unsigned char[length];
    int location;
    lh->sh->cBR->getFile(str, buffer, &location);
    if (luaL_loadbuffer(state, (const char*)buffer, length, str) || lua_pcall(state, 0, 0, 0)) {
        printf("cannot parse %s\n", str);
    }

    delete[] buffer;

    return 0;
}
Пример #19
0
static int
luaCallFunction(lua_State *L)
{
	int numparams = lua_gettop(L);
	lua_getglobal(L, "__unlua");
	AActor* unlua = (AActor*) lua_topointer(L, -1);
	lua_remove(L, -1);

	AActor* actor = (AActor*) lua_topointer(L, lua_upvalueindex(1));
	UFunction* func = (UFunction*) lua_topointer(L, lua_upvalueindex(2));
	const char* funcName_s = lua_tostring(L, lua_upvalueindex(3));
	

	if (func->NumParms == 0) {
		actor->ProcessEvent(func, NULL, NULL);
		return 0;
	}

	TFieldIterator<UProperty> It (func);
	char params[1024];
	memset(params, 0, sizeof(params));
	char* parptr = params;
	TArray<FString*> allocatedStrings;
	for (int i = 0; i < func->NumParms; ++i) {
		if (i >= numparams) {
			if (It->PropertyFlags & CPF_OptionalParm) {
				break;
			} else {
				lua_pushfstring(L, "Too few parameters for call to %s", funcName_s);
				lua_error(L);
			}
		}
		if (It->IsA(UIntProperty::StaticClass())) {
			int anint = lua_tointeger(L, i + 1);
			memcpy(parptr, &anint, It->ElementSize);
		} else if (It->IsA(UStrProperty::StaticClass())) {
			FString* astr = new FString(lua_tostring(L, i + 1));
			allocatedStrings.AddItem(astr);
			memcpy(parptr, astr, It->ElementSize);
		} else if (It->IsA(UNameProperty::StaticClass())) {
			FString astr(lua_tostring(L, i + 1));
			FName aname(*astr, FNAME_Add);
			memcpy(parptr, &aname, It->ElementSize);
		} else if (It->IsA(UByteProperty::StaticClass())) {
			*parptr = (char) lua_tointeger(L, i + 1);
		} else if (It->IsA(UBoolProperty::StaticClass())) {
			int bval = lua_toboolean(L, i + 1);
			memcpy(parptr, &bval, It->ElementSize);
		} else if (It->IsA(UFloatProperty::StaticClass())) {
			float fval = (float)lua_tonumber(L, i + 1);
			memcpy(parptr, &fval, It->ElementSize);
		} else if (It->IsA(UObjectProperty::StaticClass())) {
			UObjectProperty *uop = (UObjectProperty*) *It;
			struct UnLuaActor* ula  = (struct UnLuaActor*)
				luaL_testudata(L, i + 1, "UnrealActor");
			struct UnrealClass* ulc = (struct UnrealClass*)
				luaL_testudata(L, i + 1, "UnrealClass");
			UObject** uobj = (UObject**) parptr;
			if ((ula == NULL) && (ulc == NULL))
				*uobj = NULL;
			else {
				if (uop->PropertyClass == UClass::StaticClass()) {
					if (ulc == NULL) {
						lua_pushfstring(L, "Invalid type for parameter %d", i+1);
						lua_error(L);
					}
					*uobj = ulc->uclass;
				} else {
					if (ula->actor->IsA(uop->PropertyClass)) {
						//memcpy(parptr, ula->actor, It->ElementSize);
						*uobj = ula->actor;
					} else {
						lua_pushfstring(L, "Invalid type for parameter %d", i+1);
						lua_error(L);
					}
				}
			}
		} else {
			lua_pushfstring(L, "luaCallFunction: Unreal function %s requires "
				"parameter type not yet supported by UnLua", funcName_s);
			lua_error(L);
		}
		parptr += It->ElementSize;
		++It;
	}
	actor->ProcessEvent(func, params, NULL);
	free(params);
	while(allocatedStrings.Num())
		delete allocatedStrings.Pop();

	return 0;
}
Пример #20
0
/**
 * \brief Registers a timer into a context (table or a userdata).
 * \param timer A timer.
 * \param context_index Index of the table or userdata in the stack.
 * \param callback_ref Lua ref to the function to call when the timer finishes.
 */
void LuaContext::add_timer(
    const TimerPtr& timer,
    int context_index,
    const ScopedLuaRef& callback_ref
) {
  const void* context;
  if (lua_type(l, context_index) == LUA_TUSERDATA) {
    ExportableToLuaPtr* userdata = static_cast<ExportableToLuaPtr*>(
        lua_touserdata(l, context_index)
    );
    context = userdata->get();
  }
  else {
    context = lua_topointer(l, context_index);
  }

  callback_ref.push();

#ifndef NDEBUG
  // Sanity check: check the uniqueness of the ref.
  for (const auto& kvp: timers) {
    if (kvp.second.callback_ref.get() == callback_ref.get()) {
      std::ostringstream oss;
      oss << "Callback ref " << callback_ref.get()
          << " is already used by a timer (duplicate luaL_unref?)";
      Debug::die(oss.str());
    }
  }
#endif

  Debug::check_assertion(timers.find(timer) == timers.end(),
      "Duplicate timer in the system");

  timers[timer].callback_ref = callback_ref;
  timers[timer].context = context;

  Game* game = main_loop.get_game();
  if (game != nullptr) {
    // We are during a game: depending on the timer's context,
    // suspend the timer or not.
    if (is_map(l, context_index)
        || is_entity(l, context_index)
        || is_item(l, context_index)) {

      bool initially_suspended = false;

      // By default, we want the timer to be automatically suspended when a
      // camera movement, a dialog or the pause menu starts.
      if (!is_entity(l, context_index)) {
        // The timer normally gets suspended/resumed with the map.
        timer->set_suspended_with_map(true);

        // But in the initial state, we override that rule.
        // We initially suspend the timer only during a dialog.
        // In particular, we don't want to suspend timers created during a
        // camera movement.
        // This would be very painful for users.
        initially_suspended = game->is_dialog_enabled();
      }
      else {
        // Entities are more complex: they also get suspended when disabled
        // and when far from the camera. Therefore, they don't simply follow
        // the map suspended state.
        EntityPtr entity = check_entity(l, context_index);
        initially_suspended = entity->is_suspended() || !entity->is_enabled();
      }

      timer->set_suspended(initially_suspended);
    }
  }
}
Пример #21
0
int LuaVar::RegisterTable(lua_State *L, int valueIdx) {
	if (!lua_istable(L, valueIdx)) {
		if (lua_getmetatable(L, valueIdx) == 0) {
			return -1;
		}
		lua_pop(L, 1);
	}

	// OriginalObj couldn't be handled correctly.
	if (lua_islightuserdata(L, valueIdx)
		&& lua_topointer(L, valueIdx) == &context::llutil_address_for_internal_table) {
		return -1;
	}

	int top = lua_gettop(L);

	// Try to do "table = registry[&OriginalObj]"
	lua_pushlightuserdata(L, (void *)&context::llutil_address_for_internal_table);
	lua_rawget(L, LUA_REGISTRYINDEX);
	if (!lua_istable(L, -1)) {
		lua_pop(L, 1);

		// local newtable = {}
		lua_newtable(L);

		// setmetatable(newtable, {__mode="vk"})
		lua_newtable(L);
		lua_pushliteral(L, "__mode");
		lua_pushliteral(L, "vk");
		lua_rawset(L, -3);
		lua_setmetatable(L, -2);

		// newtable[0] = 1 -- initial index
		lua_pushnumber(L, (lua_Number)1);
		lua_rawseti(L, -2, 0);

		// registry[&OriginalObj] = newtable
		lua_pushlightuserdata(L, (void *)&context::llutil_address_for_internal_table);
		lua_pushvalue(L, -2);
		lua_rawset(L, LUA_REGISTRYINDEX);
	}

	// table is registry[&OriginalObj]
	int table = lua_gettop(L);
	int n = 0; // use after

	// Check table[valueIdx] is number.
	lua_pushvalue(L, valueIdx);
	lua_rawget(L, table);
	if (lua_isnumber(L, -1)) {
		n = (int)lua_tonumber(L, -1);
		lua_pop(L, 1);

		// Check table[n] is table.
		lua_rawgeti(L, table, n);
		if (lua_istable(L, -1)) {
			// No problems.
			lua_pop(L, 1);
		}
		else {
			lua_pop(L, 1);

			// table[n] = valueIdx, again
			lua_pushvalue(L, valueIdx);
			lua_rawseti(L, table, n);
		}
	}
	else {
		lua_pop(L, 1);

		// n = table[0]
		lua_rawgeti(L, table, 0);
		n = (int)lua_tonumber(L, -1);
		lua_pop(L, 1);

		// table[0] = n + 1
		lua_pushnumber(L, (lua_Number)(n + 1));
		lua_rawseti(L, table, 0);

		// table[valueIdx] = n
		lua_pushvalue(L, valueIdx);
		lua_pushnumber(L, (lua_Number)n);
		lua_rawset(L, table);

		// table[n] = valueIdx
		lua_pushvalue(L, valueIdx);
		lua_rawseti(L, table, n);
	}

	lua_pop(L, 1);
	assert(top == lua_gettop(L));
	(void)top;
	return n;
}
Пример #22
0
// (archive:lightuserdata) -> nil
int C_archive_CloseArchive(lua_State* L)
{
    struct QArchive* qa = (struct QArchive*)lua_topointer(L, 1);
    CloseArchive(qa);
    return 0;
}
Пример #23
0
void DisplayObjectContainer::renderChildren(lua_State *L)
{
    if (!visible)
    {
        return;
    }

    // containers can set a new view to render into, but we must restore the
    // current view after, so take a snapshot
    int viewRestore = GFX::Graphics::getView();

    // set the current view we will be rendering into.
    if (viewRestore != _view)
    {
        GFX::Graphics::setView(_view);
    }

    renderState.alpha          = parent ? parent->renderState.alpha * alpha : alpha;
    renderState.cachedClipRect = parent ? parent->renderState.cachedClipRect : (unsigned short)-1;

    int docidx = lua_gettop(L);

    lua_rawgeti(L, docidx, (int)childrenOrdinal);

    lua_rawgeti(L, -1, LSINDEXVECTOR);
    int childrenVectorIdx = lua_gettop(L);

    int numChildren = lsr_vector_get_length(L, -2);


    if (_depthSort && ((int)sSortBucket.size() < numChildren))
    {
        sSortBucket.resize(numChildren);
    }

    // Is there a cliprect? If so, set it.
    if ((clipX != 0) || (clipY != 0) || (clipWidth != 0) || (clipHeight != 0))
    {
        GFX::QuadRenderer::submit();

        Matrix        res;
        DisplayObject *stage = this;
        while (stage->parent)
        {
            stage = stage->parent;
        }

        getTargetTransformationMatrix(NULL, &res);

        int x1 = (int) ((float)clipX * res.a + res.tx) ;
        int y1 = (int) ((float)clipY * res.d + res.ty);
        int x2 = (int) ((float)clipWidth * res.a);
        int y2 = (int) ((float)clipHeight * res.d);

        renderState.cachedClipRect = GFX::Graphics::setClipRect(x1, y1, x2, y2);
    }
    else
    {
        GFX::Graphics::setClipRect(renderState.cachedClipRect);
    }

    for (int i = 0; i < numChildren; i++)
    {
        lua_rawgeti(L, childrenVectorIdx, i);

        DisplayObject *dobj = (DisplayObject *)lualoom_getnativepointer(L, -1);

        lua_rawgeti(L, -1, LSINDEXTYPE);
        dobj->type = (Type *)lua_topointer(L, -1);
        lua_pop(L, 1);

        dobj->validate(L, lua_gettop(L));

        if (!_depthSort)
        {
            renderType(L, dobj->type, dobj);
        }
        else
        {
            sSortBucket[i].index         = i;
            sSortBucket[i].displayObject = dobj;
        }

        // pop instance
        lua_pop(L, 1);
    }

    if (_depthSort)
    {
        qsort(sSortBucket.ptr(), numChildren, sizeof(DisplayObjectSort), DisplayObjectSortFunction);

        for (int i = 0; i < numChildren; i++)
        {
            DisplayObjectSort *ds = &sSortBucket[i];

            lua_rawgeti(L, childrenVectorIdx, ds->index);

            renderType(L, ds->displayObject->type, ds->displayObject);

            // pop instance
            lua_pop(L, 1);
        }
    }

    lua_settop(L, docidx);

    // Restore clip state.
    if ((clipX != 0) || (clipY != 0) || (clipWidth != 0) || (clipHeight != 0))
    {
        GFX::QuadRenderer::submit();
        GFX::Graphics::clearClipRect();
    }

    // restore view
    if (viewRestore != _view)
    {
        GFX::Graphics::setView(viewRestore);
    }
}
Пример #24
0
/*---------------------------------------------------------------------------*/ 
void lua_tinker::enum_stack(lua_State *L)
{
        int top = lua_gettop(L);
        print_error(L, "Type:%d", top);
        for(int i=1; i<=lua_gettop(L); ++i)
        {
                switch(lua_type(L, i))
                {
                case LUA_TNIL:
                        print_error(L, "\t%s", lua_typename(L, lua_type(L, i)));
                        break;
                case LUA_TBOOLEAN:
                        print_error(L, "\t%s    %s", lua_typename(L, lua_type(L, i)), lua_toboolean(L, i)?"true":"false");
                        break;
                case LUA_TLIGHTUSERDATA:
                        print_error(L, "\t%s    0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i));
                        break;
                case LUA_TNUMBER:
                        print_error(L, "\t%s    %f", lua_typename(L, lua_type(L, i)), lua_tonumber(L, i));
                        break;
                case LUA_TSTRING:
                        print_error(L, "\t%s    %s", lua_typename(L, lua_type(L, i)), lua_tostring(L, i));
                        break;
                case LUA_TTABLE:
                        print_error(L, "\t%s    0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i));
                        break;
                case LUA_TFUNCTION:
                        print_error(L, "\t%s()  0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i));
                        break;
                case LUA_TUSERDATA:
                        print_error(L, "\t%s    0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i));
                        break;
                case LUA_TTHREAD:
                        print_error(L, "\t%s", lua_typename(L, lua_type(L, i)));
                        break;
                }
        }
}
Пример #25
0
/*---------------------------------------------------------------------------*/ 
static int le_s64(lua_State *L)
{
        lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(long long)) <= 0);
        return 1;
}
Пример #26
0
/*---------------------------------------------------------------------------*/ 
static int lt_u64(lua_State *L)
{
        lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(unsigned long long)) < 0);
        return 1;
}
Пример #27
0
QString luaTrajectory::pop(lua_State *luaL, QStringList& attribs)
{
#ifdef DEBUG_OBSERVER
    printf("\ngetState - Trajectory\n\n");
    luaStackToQString(12);

    qDebug() << attribs;
#endif

    QString msg;

    // id
    msg.append(QString::number(getId()));
    msg.append(PROTOCOL_SEPARATOR);

    // subjectType
    msg.append(QString::number(subjectType));
    msg.append(PROTOCOL_SEPARATOR);

    int pos = lua_gettop(luaL);

    //------------
    int attrCounter = 0;
    int elementCounter = 0;
    // bool contains = false;
    double num = 0;
    QString text, key, attrs, elements;

    lua_pushnil(luaL);
    while(lua_next(luaL, pos ) != 0)
    {
        if (lua_type(luaL, -2) == LUA_TSTRING)
        {
            key = QString(luaL_checkstring(luaL, -2));
        }
        else
        {
            if (lua_type(luaL, -2) == LUA_TNUMBER)
            {
                char aux[100];
                double number = luaL_checknumber(luaL, -2);
                sprintf(aux, "%g", number);
                key = QString(aux);
            }
        }

        if ((attribs.contains(key)) || (key == "cells"))
        {
            attrCounter++;
            attrs.append(key);
            attrs.append(PROTOCOL_SEPARATOR);

            switch( lua_type(luaL, -1) )
            {
            case LUA_TBOOLEAN:
                attrs.append(QString::number(TObsBool));
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append(QString::number( lua_toboolean(luaL, -1)));
                attrs.append(PROTOCOL_SEPARATOR);
                break;

            case LUA_TNUMBER:
                num = luaL_checknumber(luaL, -1);
                doubleToQString(num, text, 20);
                attrs.append(QString::number(TObsNumber));
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append(text);
                attrs.append(PROTOCOL_SEPARATOR);
                break;

            case LUA_TSTRING:
                text = QString(luaL_checkstring(luaL, -1));
                attrs.append(QString::number(TObsText) );
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append( (text.isEmpty() || text.isNull() ? VALUE_NOT_INFORMED : text) );
                attrs.append(PROTOCOL_SEPARATOR);
                break;

            case LUA_TTABLE:
            {
                char result[100];
                sprintf(result, "%p", lua_topointer(luaL, -1) );
                attrs.append(QString::number(TObsText) );
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append("Lua-Address(TB): " + QString(result));
                attrs.append(PROTOCOL_SEPARATOR);

                // Recupera a tabela de cells e delega a cada
                // celula sua serialização
                if (key == "cells")
                {
                    int top = lua_gettop(luaL);

                    lua_pushnil(luaL);
                    while(lua_next(luaL, top) != 0)
                    {
                        int cellTop = lua_gettop(luaL);

                        lua_pushstring(luaL, "cObj_");
                        lua_gettable(luaL, cellTop);

                        luaCell*  cell;
                        cell = (luaCell*)Luna<luaCell>::check(L, -1);
                        lua_pop(luaL, 1);

                        // luaCell->pop(...) requer uma celula no topo da pilha
                        QString cellMsg = cell->pop(L, QStringList() << "x" << "y");
                        elements.append(cellMsg);
                        elementCounter++;

                        lua_pop(luaL, 1);
                    }
                    // break;
                }
                break;
            }

            case LUA_TUSERDATA	:
            {
                char result[100];
                sprintf(result, "%p", lua_topointer(luaL, -1) );
                attrs.append(QString::number(TObsText) );
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append("Lua-Address(UD): " + QString(result));
                attrs.append(PROTOCOL_SEPARATOR);
                break;
            }

            case LUA_TFUNCTION:
            {
                char result[100];
                sprintf(result, "%p", lua_topointer(luaL, -1) );
                attrs.append(QString::number(TObsText) );
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append(QString("Lua-Address(FT): ") + QString(result));
                attrs.append(PROTOCOL_SEPARATOR);
                break;
            }

            default:
            {
                char result[100];
                sprintf(result, "%p", lua_topointer(luaL, -1) );
                attrs.append(QString::number(TObsText) );
                attrs.append(PROTOCOL_SEPARATOR);
                attrs.append(QString("Lua-Address(O): ") + QString(result));
                attrs.append(PROTOCOL_SEPARATOR);
                break;
            }
            }
        }
        lua_pop(luaL, 1);
    }

    // #attrs
    msg.append(QString::number(attrCounter));
    msg.append(PROTOCOL_SEPARATOR );

    // #elements
    msg.append(QString::number(elementCounter));
    msg.append(PROTOCOL_SEPARATOR );
    msg.append(attrs);

    msg.append(PROTOCOL_SEPARATOR);
    msg.append(elements);
    msg.append(PROTOCOL_SEPARATOR);

#ifdef DEBUG_OBSERVER
    // save(msg);
    // qDebug() << msg.split(PROTOCOL_SEPARATOR); //, QString::SkipEmptyParts);
#endif

    return msg;
}
Пример #28
0
	const void* LuaState::ToPointer(int index) const
	{
		return lua_topointer(m_state, index);
	}
Пример #29
0
/*
   =============================================================================
    statement:query(var1, var2, var3...): Injects variables into a prepared 
    statement and returns the number of rows affected.
   =============================================================================
 */
int lua_db_prepared_query(lua_State *L)
{
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    lua_db_prepared_statement  *st = 0;
    apr_status_t     rc = 0;
    const char       **vars;
    int              x, have;
    /*~~~~~~~~~~~~~~~~~~~~~~~*/
    
    /* Fetch the prepared statement and the vars passed */
    luaL_checktype(L, 1, LUA_TTABLE);
    lua_rawgeti(L, 1, 0);
    luaL_checktype(L, -1, LUA_TUSERDATA);
    st = (lua_db_prepared_statement*) lua_topointer(L, -1);
    
    /* Check if we got enough variables passed on to us.
     * This, of course, only works for prepped statements made through lua. */
    have = lua_gettop(L) - 2;
    if (st->variables != -1 && have < st->variables ) {
        lua_pushboolean(L, 0);
        lua_pushfstring(L, 
                "Error in executing prepared statement: Expected %d arguments, got %d.", 
                st->variables, have);
        return 2;
    }
    vars = apr_pcalloc(st->db->pool, have*sizeof(char *));
    for (x = 0; x < have; x++) {
        vars[x] = lua_tostring(L, x + 2);
    }

    /* Fire off the query */
    if (st->db && st->db->alive) {

        /*~~~~~~~~~~~~~~*/
        int affected = 0;
        /*~~~~~~~~~~~~~~*/

        rc = apr_dbd_pquery(st->db->driver, st->db->pool, st->db->handle,
                                &affected, st->statement, have, vars);
        if (rc == APR_SUCCESS) {
            lua_pushinteger(L, affected);
            return 1;
        }
        else {

            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
            const char  *err = apr_dbd_error(st->db->driver, st->db->handle, rc);
            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

            lua_pushnil(L);
            if (err) {
                lua_pushstring(L, err);
                return 2;
            }
            return 1;
        }
    }

    lua_pushboolean(L, 0);
    lua_pushliteral(L, 
            "Database connection seems to be closed, please reacquire it.");
    return (2);
}
Пример #30
0
/*
   =============================================================================
    statement:select(var1, var2, var3...): Injects variables into a prepared 
    statement and returns the number of rows matching the query.
   =============================================================================
 */
int lua_db_prepared_select(lua_State *L)
{
    /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    lua_db_prepared_statement  *st = 0;
    apr_status_t     rc = 0;
    const char       **vars;
    int              x, have;
    /*~~~~~~~~~~~~~~~~~~~~~~~*/
    
    /* Fetch the prepared statement and the vars passed */
    luaL_checktype(L, 1, LUA_TTABLE);
    lua_rawgeti(L, 1, 0);
    luaL_checktype(L, -1, LUA_TUSERDATA);
    st = (lua_db_prepared_statement*) lua_topointer(L, -1);
    
    /* Check if we got enough variables passed on to us.
     * This, of course, only works for prepped statements made through lua. */
    have = lua_gettop(L) - 2;
    if (st->variables != -1 && have < st->variables ) {
        lua_pushboolean(L, 0);
        lua_pushfstring(L, 
                "Error in executing prepared statement: Expected %d arguments, got %d.", 
                st->variables, have);
        return 2;
    }
    vars = apr_pcalloc(st->db->pool, have*sizeof(char *));
    for (x = 0; x < have; x++) {
        vars[x] = lua_tostring(L, x + 2);
    }

    /* Fire off the query */
    if (st->db && st->db->alive) {

        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
        int cols;
        apr_dbd_results_t   *results = 0;
        /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

        rc = apr_dbd_pselect(st->db->driver, st->db->pool, st->db->handle,
                                &results, st->statement, 0, have, vars);
        if (rc == APR_SUCCESS) {

            /*~~~~~~~~~~~~~~~~~~~~~*/
            lua_db_result_set *resultset;
            /*~~~~~~~~~~~~~~~~~~~~~*/

            cols = apr_dbd_num_cols(st->db->driver, results);
            lua_newtable(L);
            resultset = lua_newuserdata(L, sizeof(lua_db_result_set));
            resultset->cols = cols;
            resultset->driver = st->db->driver;
            resultset->pool = st->db->pool;
            resultset->rows = apr_dbd_num_tuples(st->db->driver, results);
            resultset->results = results;
            luaL_newmetatable(L, "lua_apr.dbselect");
            lua_pushliteral(L, "__call");
            lua_pushcfunction(L, lua_db_get_row);
            lua_rawset(L, -3);
            lua_setmetatable(L, -3);
            lua_rawseti(L, -2, 0);
            return 1;
            
        }
        else {

            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
            const char  *err = apr_dbd_error(st->db->driver, st->db->handle, rc);
            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

            lua_pushnil(L);
            if (err) {
                lua_pushstring(L, err);
                return 2;
            }
            return 1;
        }
    }

    lua_pushboolean(L, 0);
    lua_pushliteral(L, 
            "Database connection seems to be closed, please reacquire it.");
    return (2);
}