Beispiel #1
0
int lua_Curve_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_TNUMBER &&
                lua_type(state, 2) == LUA_TNUMBER)
            {
                // Get parameter 1 off the stack.
                unsigned int param1 = (unsigned int)luaL_checkunsigned(state, 1);

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

                void* returnPtr = (void*)Curve::create(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, "Curve");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_Curve_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;
}
Beispiel #2
0
int lua_Model_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:
        {
            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<Mesh> param1 = gameplay::ScriptUtil::getObjectPointer<Mesh>(1, "Mesh", false, &param1Valid);
                if (!param1Valid)
                {
                    lua_pushstring(state, "Failed to convert parameter 1 to type 'Mesh'.");
                    lua_error(state);
                }

                void* returnPtr = ((void*)Model::create(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, "Model");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_Model_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).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Beispiel #3
0
/*
** When creating file handles, always creates a 'closed' file handle
** before opening the actual file; so, if there is a memory error, the
** handle is in a consistent state.
*/
static LStream *newprefile (lua_State *L) {
  LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream));
  p->closef = NULL;  /* mark file handle as 'closed' */
  luaL_setmetatable(L, LUA_FILEHANDLE);
  return p;
}
Beispiel #4
0
static int tek_lib_exec_run(lua_State *L)
{
	struct LuaExecTask *lexec = tek_lib_exec_check(L);
	struct TExecBase *TExecBase = lexec->exec;
	struct LuaExecChild *ctx;
	const char *fname = TNULL;
	const char *chunk = TNULL;
	const char *taskname = TNULL;
	size_t extralen = 0;
	struct THook hook;
	TTAGITEM tags[2];
	int nremove = 1;
	TBOOL abort = TTRUE;
	
	for (;;)
	{
		if (lua_istable(L, 1))
		{
			lua_getfield(L, 1, "abort");
			if (lua_isboolean(L, -1))
				abort = lua_toboolean(L, -1);
			lua_pop(L, 1);
			lua_getfield(L, 1, "taskname");
			taskname = lua_tostring(L, -1);
			nremove = 2;
			lua_getfield(L, 1, "func");
			if (!lua_isnoneornil(L, -1))
				break;
			lua_pop(L, 1);
			lua_getfield(L, 1, "filename");
			if (!lua_isnoneornil(L, -1))
				break;
			lua_pop(L, 1);
			lua_getfield(L, 1, "chunk");
			if (!lua_isnoneornil(L, -1))
			{
				chunk = luaL_checklstring(L, -1, &extralen);
				break;
			}
			luaL_error(L, "required argument missing");
		}
		lua_pushvalue(L, 1);
		break;
	}
	
	if (!chunk)
	{
		if (lua_type(L, -1) == LUA_TSTRING)
			fname = luaL_checklstring(L, -1, &extralen);
		else if (lua_isfunction(L, -1) && !lua_iscfunction(L, -1))
			chunk = tek_lib_exec_dump(L, &extralen);
		else
			luaL_error(L, "not a Lua function, filename or table");
	}
	
	ctx = lua_newuserdata(L, sizeof(struct LuaExecChild) + extralen + 1);
	memset(ctx, 0, sizeof *ctx);
	ctx->exec = lexec->exec;
	ctx->parent = lexec;
	ctx->taskname = tek_lib_exec_taskname(ctx->atomname, taskname);
	ctx->abort = abort;
	
	if (fname)
	{
		ctx->fname = (char *) (ctx + 1);
		strcpy(ctx->fname, (char *) fname);
	}
	else if (chunk)
	{
		memcpy(ctx + 1, chunk, extralen);
		ctx->chunklen = extralen;
	}
	
	/* remove arguments under userdata */
	while (nremove--)
		lua_remove(L, -2);

	ctx->numargs = lua_gettop(L) - 2;
	
	/* push arg[0] on the stack, will be extraarg */
	lua_getglobal(L, "arg");
	if (lua_istable(L, -1))
	{
		lua_rawgeti(L, -1, 0);
		lua_remove(L, -2);
	}
	if (lua_type(L, -1) != LUA_TSTRING)
	{
		lua_pop(L, 1);
		lua_pushnil(L);
	}
	ctx->args = tek_lib_exec_getargs(L, TExecBase, 2, ctx->numargs++, 1);
	lua_pop(L, 1);
	
	ctx->L = lua_newstate(tek_lib_exec_allocf, TExecBase);
	if (ctx->L == TNULL)
	{
		tek_lib_exec_freeargs(TExecBase, ctx->args, ctx->numargs);
		luaL_error(L, "cannot create interpreter");
	}
	
	tags[0].tti_Tag = TTask_UserData;
	tags[0].tti_Value = (TTAG) ctx;
	tags[1].tti_Tag = TTAG_DONE;
	TInitHook(&hook, tek_lib_exec_run_dispatch, ctx);
	ctx->task = TCreateTask(&hook, tags);
	if (ctx->task == TNULL)
	{
		tek_lib_exec_freectxargs(ctx);
		lua_pop(L, 1);
		lua_pushnil(L);
		return 1;
	}
	
	lua_getfield(L, LUA_REGISTRYINDEX, TEK_LIB_TASK_CLASSNAME);
	lua_setmetatable(L, -2);
	lua_pushvalue(L, -1);
	ctx->ref = luaL_ref(L, lua_upvalueindex(2));
	if (ctx->abort)
		tek_lib_exec_register_task_hook(L, TExecBase);
	return 1;
}
Beispiel #5
0
int lua_Model_getSkin(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))
            {
                Model* instance = getInstance(state);
                void* returnPtr = ((void*)instance->getSkin());
                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, "MeshSkin");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_Model_getSkin - 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).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Beispiel #6
0
/// Wrapper around lua_newuserdata.
///
/// This is internal.  The public type-safe interface of this method should be
/// used instead.
///
/// \param size The second parameter to lua_newuserdata.
///
/// \return The return value of lua_newuserdata.
///
/// \warning Terminates execution if there is not enough memory.
void*
lutok::state::new_userdata_voidp(const size_t size)
{
    return lua_newuserdata(_pimpl->lua_state, size);
}
int lua_TextureSampler_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:
        {
            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.
                Texture* param1 = ScriptUtil::getObjectPointer<Texture>(1, "Texture", false);

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

                return 1;
            }
            else if ((lua_type(state, 1) == LUA_TSTRING || lua_type(state, 1) == LUA_TNIL))
            {
                // Get parameter 1 off the stack.
                const char* param1 = ScriptUtil::getString(1, false);

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

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

                // Get parameter 2 off the stack.
                bool param2 = ScriptUtil::luaCheckBool(state, 2);

                void* returnPtr = (void*)Texture::Sampler::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, "TextureSampler");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }
            else
            {
                lua_pushstring(state, "lua_TextureSampler_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 2).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
static void json_create_config(lua_State *l)
{
    json_config_t *cfg;
    int i;

    cfg = (json_config_t *)lua_newuserdata(l, sizeof(*cfg));

    /* Create GC method to clean up strbuf */
    lua_newtable(l);
    lua_pushcfunction(l, json_destroy_config);
    lua_setfield(l, -2, "__gc");
    lua_setmetatable(l, -2);

    cfg->encode_sparse_convert = DEFAULT_SPARSE_CONVERT;
    cfg->encode_sparse_ratio = DEFAULT_SPARSE_RATIO;
    cfg->encode_sparse_safe = DEFAULT_SPARSE_SAFE;
    cfg->encode_max_depth = DEFAULT_ENCODE_MAX_DEPTH;
    cfg->decode_max_depth = DEFAULT_DECODE_MAX_DEPTH;
    cfg->encode_invalid_numbers = DEFAULT_ENCODE_INVALID_NUMBERS;
    cfg->decode_invalid_numbers = DEFAULT_DECODE_INVALID_NUMBERS;
    cfg->encode_keep_buffer = DEFAULT_ENCODE_KEEP_BUFFER;
    cfg->encode_number_precision = DEFAULT_ENCODE_NUMBER_PRECISION;

#if DEFAULT_ENCODE_KEEP_BUFFER > 0
    strbuf_init(&cfg->encode_buf, 0);
#endif

    /* Decoding init */

    /* Tag all characters as an error */
    for (i = 0; i < 256; i++)
        cfg->ch2token[i] = T_ERROR;

    /* Set tokens that require no further processing */
    cfg->ch2token['{'] = T_OBJ_BEGIN;
    cfg->ch2token['}'] = T_OBJ_END;
    cfg->ch2token['['] = T_ARR_BEGIN;
    cfg->ch2token[']'] = T_ARR_END;
    cfg->ch2token[','] = T_COMMA;
    cfg->ch2token[':'] = T_COLON;
    cfg->ch2token['\0'] = T_END;
    cfg->ch2token[' '] = T_WHITESPACE;
    cfg->ch2token['\t'] = T_WHITESPACE;
    cfg->ch2token['\n'] = T_WHITESPACE;
    cfg->ch2token['\r'] = T_WHITESPACE;

    /* Update characters that require further processing */
    cfg->ch2token['f'] = T_UNKNOWN;     /* false? */
    cfg->ch2token['i'] = T_UNKNOWN;     /* inf, ininity? */
    cfg->ch2token['I'] = T_UNKNOWN;
    cfg->ch2token['n'] = T_UNKNOWN;     /* null, nan? */
    cfg->ch2token['N'] = T_UNKNOWN;
    cfg->ch2token['t'] = T_UNKNOWN;     /* true? */
    cfg->ch2token['"'] = T_UNKNOWN;     /* string? */
    cfg->ch2token['+'] = T_UNKNOWN;     /* number? */
    cfg->ch2token['-'] = T_UNKNOWN;
    for (i = 0; i < 10; i++)
        cfg->ch2token['0' + i] = T_UNKNOWN;

    /* Lookup table for parsing escape characters */
    for (i = 0; i < 256; i++)
        cfg->escape2char[i] = 0;          /* String error */
    cfg->escape2char['"'] = '"';
    cfg->escape2char['\\'] = '\\';
    cfg->escape2char['/'] = '/';
    cfg->escape2char['b'] = '\b';
    cfg->escape2char['t'] = '\t';
    cfg->escape2char['n'] = '\n';
    cfg->escape2char['f'] = '\f';
    cfg->escape2char['r'] = '\r';
    cfg->escape2char['u'] = 'u';          /* Unicode parsing required */
}
Beispiel #9
0
static int hj_parse_message(lua_State *lua)
{
  lsb_lua_sandbox *lsb = static_cast<lsb_lua_sandbox *>
      (lua_touserdata(lua, lua_upvalueindex(1)));
  if (!lsb) {
    return luaL_error(lua, "%s() invalid lightuserdata", __FUNCTION__);
  }
  int n = lua_gettop(lua);
  int idx = 1;

  lsb_heka_message *msg = NULL;
  lsb_heka_sandbox *hsb = static_cast<lsb_heka_sandbox *>(lsb_get_parent(lsb));
  if (hsb->type == 'i') {
    luaL_argcheck(lua, n >= 2 && n <= 4, 0, "invalid number of arguments");
    heka_stream_reader *hsr = static_cast<heka_stream_reader *>
        (luaL_checkudata(lua, 1, mozsvc_heka_stream_reader));
    msg = &hsr->msg;
    idx = 2;
  } else {
    luaL_argcheck(lua, n >= 1 && n <= 3, 0, "invalid number of arguments");
    if (!hsb->msg || !hsb->msg->raw.s) {
      return luaL_error(lua, "no active message");
    }
    msg = hsb->msg;
  }

  lsb_const_string json = read_message(lua, idx, msg);
  if (!json.s) return luaL_error(lua, "field not found");

  char *inflated = NULL;
#ifdef HAVE_ZLIB
  // automatically handle gzipped strings (optimization for Mozilla telemetry
  // messages)
  if (json.len > 2) {
    if (json.s[0] == 0x1f && (unsigned char)json.s[1] == 0x8b) {
      size_t mms = (size_t)lua_tointeger(lua, lua_upvalueindex(2));
      inflated = lsb_ungzip(json.s, json.len, mms, NULL);
      if (!inflated) return luaL_error(lua, "lsb_ungzip failed");
    }
  }
#endif

  heka_json *hj = static_cast<heka_json *>(lua_newuserdata(lua, sizeof*hj));
  hj->doc = new rj::Document;
  hj->val = NULL;
  hj->insitu = inflated;
  hj->refs =  new std::set<rj::Value *>;
  luaL_getmetatable(lua, mozsvc_heka_json);
  lua_setmetatable(lua, -2);

  if (!hj->doc || !hj->refs) {
    lua_pushstring(lua, "memory allocation failed");
    return lua_error(lua);
  }

  bool err = false;
  if (hj->insitu) {
    if (hj->doc->ParseInsitu<rj::kParseStopWhenDoneFlag>(hj->insitu)
        .HasParseError()) {
      err = true;
      lua_pushfstring(lua, "failed to parse offset:%f %s",
                      (lua_Number)hj->doc->GetErrorOffset(),
                      rj::GetParseError_En(hj->doc->GetParseError()));
    }
  } else {
    rj::MemoryStream ms(json.s, json.len);
    if (hj->doc->ParseStream<0, rj::UTF8<> >(ms).HasParseError()) {
      err = true;
      lua_pushfstring(lua, "failed to parse offset:%f %s",
                      (lua_Number)hj->doc->GetErrorOffset(),
                      rj::GetParseError_En(hj->doc->GetParseError()));
    }
  }

  if (err) return lua_error(lua);
  hj->refs->insert(hj->doc);
  return 1;
}
Beispiel #10
0
int lua_Rectangle__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 Rectangle();
            if (returnPtr)
            {
                ScriptUtil::LuaObject* object = (ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(ScriptUtil::LuaObject));
                object->instance = returnPtr;
                object->owns = true;
                luaL_getmetatable(state, "Rectangle");
                lua_setmetatable(state, -2);
            }
            else
            {
                lua_pushnil(state);
            }

            return 1;
            break;
        }
        case 1:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TNIL))
            {
                // Get parameter 1 off the stack.
                Rectangle* param1 = ScriptUtil::getObjectPointer<Rectangle>(1, "Rectangle", true);

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

                return 1;
            }
            else
            {
                lua_pushstring(state, "lua_Rectangle__init - Failed to match the given parameters to a valid function signature.");
                lua_error(state);
            }
            break;
        }
        case 2:
        {
            if (lua_type(state, 1) == LUA_TNUMBER &&
                lua_type(state, 2) == 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);

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

                return 1;
            }
            else
            {
                lua_pushstring(state, "lua_Rectangle__init - Failed to match the given parameters to a valid function signature.");
                lua_error(state);
            }
            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 Rectangle(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, "Rectangle");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }
            else
            {
                lua_pushstring(state, "lua_Rectangle__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 4).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Beispiel #11
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)
            {
                ScriptUtil::LuaObject* object = (ScriptUtil::LuaObject*)lua_newuserdata(state, sizeof(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:
        {
            if ((lua_type(state, 1) == LUA_TUSERDATA || lua_type(state, 1) == LUA_TNIL))
            {
                // Get parameter 1 off the stack.
                ScriptUtil::LuaArray<Ray> param1 = ScriptUtil::getObjectPointer<Ray>(1, "Ray", true);

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

                return 1;
            }
            else
            {
                lua_pushstring(state, "lua_Ray__init - 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, 1) == LUA_TNIL) &&
                (lua_type(state, 2) == LUA_TUSERDATA || lua_type(state, 2) == LUA_TNIL))
            {
                // Get parameter 1 off the stack.
                ScriptUtil::LuaArray<Vector3> param1 = ScriptUtil::getObjectPointer<Vector3>(1, "Vector3", true);

                // Get parameter 2 off the stack.
                ScriptUtil::LuaArray<Vector3> param2 = ScriptUtil::getObjectPointer<Vector3>(2, "Vector3", true);

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

                return 1;
            }
            else
            {
                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 or 2).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Beispiel #12
0
LoadResult SyntaxReader::load ( const string& langDefPath, const string& pluginReadFilePath, OutputType outputType, bool clear )
{

    currentPath=langDefPath;
    disableHighlighting=false;
    
    if (!Platform::fileExists(langDefPath)){
      return LOAD_FAILED;
    }

    try {

	if (luaState) delete luaState;
	luaState=new Diluculum::LuaState();

	Diluculum::LuaState& ls=*luaState;
	initLuaState(ls, langDefPath, pluginReadFilePath, outputType);

	lua_register (ls.getState(),"AddKeyword",luaAddKeyword);
	
	SyntaxReader **s = (SyntaxReader **)lua_newuserdata(ls.getState(), sizeof(SyntaxReader *));
	*s=this;
	lua_setglobal(ls.getState(), GLOBAL_INSTANCE_NAME);

        // ececute script and read values
        ls.doFile (langDefPath);

        langDesc = ls["Description"].value().asString();

	if (pluginChunks.size()){
	  Diluculum::LuaValueList params;
	  params.push_back(langDesc);
	  for (unsigned int i=0;i<pluginChunks.size();i++){
	    ls.call(*pluginChunks[i], params, "syntax user function");
	  }
	}

	Diluculum::LuaValueMap globals = ls.globals();

        ignoreCase=readFlag(ls["IgnoreCase"]);
        reformatCode=readFlag(ls["EnableIndentation"]);
        disableHighlighting=readFlag(ls["DisableHighlighting"]);

        int idx=1;
        int keywordIdx=0;
        int kwId=0;
        char kwName[5]={0};
        while (ls["Keywords"][idx].value() !=Diluculum::Nil) {
            keywordIdx=ls["Keywords"][idx]["Id"].value().asNumber();
            snprintf(kwName, sizeof(kwName), "kw%c", ('a'+keywordIdx-1)); // TODO kwa -> kw1...
            kwId= generateNewKWClass ( kwName );

            if (ls["Keywords"][idx]["List"].value()!=Diluculum::Nil) {
                int listIdx=1;
                Diluculum::LuaVariable luaList=ls["Keywords"][idx]["List"];
                while (luaList[listIdx].value()!=Diluculum::Nil) {
                    keywords.insert ( make_pair ( luaList[listIdx].value().asString(), kwId ) );
                    ++listIdx;
                }
            } else if (ls["Keywords"][idx]["Regex"].value()!=Diluculum::Nil) {
                string reString=StringTools::trim(ls["Keywords"][idx]["Regex"].value().asString());
                int captGroup=-1;
                if (ls["Keywords"][idx]["Group"].value()!=Diluculum::Nil) {
                    captGroup=ls["Keywords"][idx]["Group"].value().asNumber();
                }
                regex.push_back ( new RegexElement ( KEYWORD, KEYWORD_END, reString, kwId, captGroup ) );
            }
            idx++;
        }

        if (globals.count("Comments")) {

            int listIdx=1;
            int openDelimId=0;
            int closeDelimId=0;
            while (ls["Comments"][listIdx].value()!=Diluculum::Nil) {
                if (ls["Comments"][listIdx]["Block"].value().asBoolean()) {

                    if (ls["Comments"][listIdx]["Nested"].value()!=Diluculum::Nil)
                        allowNestedComments = ls["Comments"][listIdx]["Nested"].value().asBoolean();

                    string openDelim=StringTools::trim(ls["Comments"][listIdx]["Delimiter"][1].value().asString());
		    RegexElement* elem=new RegexElement ( ML_COMMENT,ML_COMMENT_END, openDelim, 0, -1 );
		    openDelimId=elem->instanceId;
		    regex.push_back ( elem );
                    
                    string closeDelim=StringTools::trim(ls["Comments"][listIdx]["Delimiter"][2].value().asString());
                    
		    elem= new RegexElement ( ML_COMMENT_END,ML_COMMENT_END, closeDelim, 0, -1 );
		    closeDelimId=elem->instanceId;
		    regex.push_back ( elem);
                    
                    delimiterDistinct[openDelimId]=openDelim!=closeDelim;
                    delimiterDistinct[closeDelimId]=openDelim!=closeDelim;
                    delimIds2[closeDelimId]=openDelimId;

                } else {
                    regex.push_back ( new RegexElement ( SL_COMMENT, SL_COMMENT_END, StringTools::trim(ls["Comments"][listIdx]["Delimiter"][1].value().asString()), 0, -1 ) );
                }
                ++listIdx;
            }

        }

        //move behind comment section because of fortran comments (^cC.*$)
        string re_digit = StringTools::trim(ls["Digits"].value().asString());
        string re_identifier= StringTools::trim(ls["Identifiers"].value().asString());

        // insert identifier and number regex after keyword regexes
        regex.push_back ( new RegexElement ( IDENTIFIER_BEGIN, IDENTIFIER_END,
                                             re_identifier  ) );
        regex.push_back ( new RegexElement ( NUMBER, NUMBER_END,
                                              re_digit  ) );

        if (globals.count("Strings")) {

            if (ls["Strings"]["RawPrefix"].value()!=Diluculum::Nil) {
                rawStringPrefix=ls["Strings"]["RawPrefix"].value().asString().at(0);
            }

            if (ls["Strings"]["Delimiter"].value()!=Diluculum::Nil) {
                
		RegexElement* elem=new RegexElement ( STRING,STRING_END, StringTools::trim( ls["Strings"]["Delimiter"].value().asString()), 0, -1 );
		delimiterDistinct[elem->instanceId]=true;
		regex.push_back (elem );
            }
            if (ls["Strings"]["Interpolation"].value()!=Diluculum::Nil) {
		RegexElement* elem=new RegexElement ( STRING_INTERPOLATION, STRING_INTERPOLATION_END, StringTools::trim( ls["Strings"]["Interpolation"].value().asString()), 0, -1 );
		regex.push_back (elem );
            }

            if (ls["Strings"]["DelimiterPairs"].value()!=Diluculum::Nil) {

                int listIdx=1;
                int openDelimId=0;
                int closeDelimId=0;
                while (ls["Strings"]["DelimiterPairs"][listIdx].value()!=Diluculum::Nil) {

                    string openDelim=StringTools::trim(ls["Strings"]["DelimiterPairs"][listIdx]["Open"].value().asString());
                    
		    RegexElement* elem =new RegexElement(STRING, STRING_END, openDelim, 0, -1);
		    openDelimId=elem->instanceId;
		    regex.push_back( elem );
                    
                    string closeDelim=StringTools::trim(ls["Strings"]["DelimiterPairs"][listIdx]["Close"].value().asString());

		    elem = new RegexElement(STRING_END, STRING_END, closeDelim, 0, -1);
		    closeDelimId=elem->instanceId;
		    regex.push_back( elem );

                    delimIds2[closeDelimId]=openDelimId;

		    if (ls["Strings"]["DelimiterPairs"][listIdx]["Raw"].value()!=Diluculum::Nil){
		      rawStringOpenDelims[openDelimId]=ls["Strings"]["DelimiterPairs"][listIdx]["Raw"].value().asBoolean();
		    }

                    ++listIdx;
                }
            }

            string  escRegex=(ls["Strings"]["Escape"].value()==Diluculum::Nil)?REGEX_ESCSEQ:ls["Strings"]["Escape"].value().asString();
            
            regex.push_back ( new RegexElement ( ESC_CHAR,ESC_CHAR_END, StringTools::trim(escRegex), 0, -1 ) );
            
        }

        if (globals.count("PreProcessor")) {
            
            regex.push_back ( new RegexElement ( DIRECTIVE,DIRECTIVE_END, StringTools::trim(ls["PreProcessor"]["Prefix"].value().asString()), 0, -1 ) );
            
            if (ls["PreProcessor"]["Continuation"].value()!=Diluculum::Nil) {
                continuationChar=ls["PreProcessor"]["Continuation"].value().asString().at(0);
            }
        }

        if (globals.count("Operators")) {
            regex.push_back ( new RegexElement ( SYMBOL,SYMBOL_END, StringTools::trim( ls["Operators"].value().asString()), 0, -1 ) );
        }

        if (globals.count("NestedSections")) {

            int listIdx=1;
            while (ls["NestedSections"][listIdx].value()!=Diluculum::Nil) {

                string lang= ls["NestedSections"][listIdx]["Lang"].value().asString();
                string openDelim=StringTools::trim(ls["NestedSections"][listIdx]["Delimiter"][1].value().asString());
                regex.insert(regex.begin(), 1, new RegexElement(EMBEDDED_CODE_BEGIN, EMBEDDED_CODE_BEGIN, openDelim, 0, -1, lang));
   
                string closeDelim=StringTools::trim(ls["NestedSections"][listIdx]["Delimiter"][2].value().asString());
                exitDelimiters[getNewPath(lang)] = closeDelim;

                ++listIdx;
            }

        }
        
        if (globals.count("HeaderInjection")) {
            headerInjection+= ls["HeaderInjection"].value().asString();
        }
        
        if (globals.count("FooterInjection")) {
            footerInjection+= ls["FooterInjection"].value().asString();
        }

        // load hook functions
        if (globals.count("OnStateChange")) {
            validateStateChangeFct=new Diluculum::LuaFunction(ls["OnStateChange"].value().asFunction());
        }
        if (globals.count("Decorate")) {
            decorateFct=new Diluculum::LuaFunction(ls["Decorate"].value().asFunction());
        }

    } catch (Diluculum::LuaError err) {
        luaErrorMsg = string(err.what());
        return LOAD_FAILED_LUA;
    }
    return LOAD_OK;
}
Beispiel #13
0
void* LuaInterface::newUserdata(int size)
{
    return lua_newuserdata(L, size);
}
Beispiel #14
0
/*
** Read the options specified in the ini file.
**
*/
void CMeasureScript::ReadOptions(CConfigParser& parser, const WCHAR* section)
{
	CMeasure::ReadOptions(parser, section);

	std::wstring file = parser.ReadString(section, L"ScriptFile", L"");

	if (!file.empty())
	{
		if (m_MeterWindow)
		{
			m_MeterWindow->MakePathAbsolute(file);
		}

		if (!m_Initialized ||
			wcscmp(file.c_str(), m_ScriptFile.c_str()) != 0)
		{
			DeleteLuaScript();

			lua_State* L = LuaManager::GetState();
			m_ScriptFile = file;
			m_LuaScript = new LuaScript(m_ScriptFile.c_str());

			if (m_LuaScript->IsInitialized())
			{
				m_HasInitializeFunction = m_LuaScript->IsFunction(g_InitializeFunctionName);
				m_HasUpdateFunction = m_LuaScript->IsFunction(g_UpdateFunctionName);
				m_HasGetStringFunction = m_LuaScript->IsFunction(g_GetStringFunctionName);  // For backwards compatbility

				if (m_HasGetStringFunction)
				{
					LogWithArgs(LOG_WARNING, L"Script: Using deprecated GetStringValue() in [%s]", m_Name.c_str());
				}

				lua_rawgeti(L, LUA_GLOBALSINDEX, m_LuaScript->GetRef());

				*(CMeterWindow**)lua_newuserdata(L, sizeof(CMeterWindow*)) = m_MeterWindow;
				lua_getglobal(L, "CMeterWindow");
				lua_setmetatable(L, -2);
				lua_setfield(L, -2, "SKIN");

				*(CMeasure**)lua_newuserdata(L, sizeof(CMeasure*)) = this;
				lua_getglobal(L, "CMeasure");
				lua_setmetatable(L, -2);
				lua_setfield(L, -2, "SELF");

				// For backwards compatibility
				lua_getfield(L, -1, "PROPERTIES");
				if (lua_isnil(L, -1) == 0)
				{
					lua_pushnil(L);
					
					// Look in the table for values to read from the section
					while (lua_next(L, -2))
					{
						lua_pop(L, 1);
						const char* strKey = lua_tostring(L, -1);

						std::wstring wstrKey = ConvertToWide(strKey);
						const std::wstring& wstrValue = parser.ReadString(section, wstrKey.c_str(), L"");

						if (!wstrValue.empty())
						{
							LuaManager::PushWide(L, wstrValue.c_str());
							lua_setfield(L, -3, strKey);
						}
					}
				}

				// Pop PROPERTIES table and our table
				lua_pop(L, 2);
			}
			else
			{
				DeleteLuaScript();
			}
		}
	}
	else
	{
		LogWithArgs(LOG_ERROR, L"Script: File not valid in [%s]", m_Name.c_str());
		DeleteLuaScript();
	}
}
Beispiel #15
0
static void net_server_connected(void *arg) // for tcp only
{
  NODE_DBG("net_server_connected is called.\n");
  struct espconn *pesp_conn = arg;
  int i = 0;
  lnet_userdata *skt = NULL;
  if(pesp_conn == NULL)
    return;

#if 0
  char temp[20] = {0};
  c_sprintf(temp, IPSTR, IP2STR( &(pesp_conn->proto.tcp->remote_ip) ) );
  NODE_DBG("remote ");
  NODE_DBG(temp);
  NODE_DBG(":");
  NODE_DBG("%d",pesp_conn->proto.tcp->remote_port);
  NODE_DBG(" connected.\n");
#endif

  for(i=0;i<MAX_SOCKET;i++){
    if(socket[i] == LUA_NOREF)  // found empty slot
    {
      break;
    }
  }
  if(i>=MAX_SOCKET) // can't create more socket
  {
    NODE_ERR("MAX_SOCKET\n");
    pesp_conn->reverse = NULL;    // not accept this conn
    if(pesp_conn->proto.tcp->remote_port || pesp_conn->proto.tcp->local_port)
      espconn_disconnect(pesp_conn);
    return;
  }

  if(tcpserver_cb_connect_ref == LUA_NOREF)
    return;
  if(!gL)
    return;

  lua_rawgeti(gL, LUA_REGISTRYINDEX, tcpserver_cb_connect_ref);  // get function
  // create a new client object
  skt = (lnet_userdata *)lua_newuserdata(gL, sizeof(lnet_userdata));

  if(!skt){
    NODE_ERR("can't newudata\n");
    lua_pop(gL, 1);
    return;
  }
  // set its metatable
  luaL_getmetatable(gL, "net.socket");
  lua_setmetatable(gL, -2);
  // pre-initialize it, in case of errors
  skt->self_ref = LUA_NOREF;
  lua_pushvalue(gL, -1);  // copy the top of stack
  skt->self_ref = luaL_ref(gL, LUA_REGISTRYINDEX);    // ref to it self, for module api to find the userdata
  socket[i] = skt->self_ref;  // save to socket array
  socket_num++;
  skt->cb_connect_ref = LUA_NOREF;  // this socket already connected
  skt->cb_reconnect_ref = LUA_NOREF;
  skt->cb_disconnect_ref = LUA_NOREF;

  skt->cb_receive_ref = LUA_NOREF;
  skt->cb_send_ref = LUA_NOREF;
  skt->cb_dns_found_ref = LUA_NOREF;

#ifdef CLIENT_SSL_ENABLE
  skt->secure = 0;    // as a server SSL is not supported.
#endif

  skt->pesp_conn = pesp_conn;   // point to the espconn made by low level sdk
  pesp_conn->reverse = skt;   // let espcon carray the info of this userdata(net.socket)

  espconn_regist_recvcb(pesp_conn, net_socket_received);
  espconn_regist_sentcb(pesp_conn, net_socket_sent);
  espconn_regist_disconcb(pesp_conn, net_server_disconnected);
  espconn_regist_reconcb(pesp_conn, net_server_reconnected);

  // now socket[i] has the client ref, and stack top has the userdata
  lua_call(gL, 1, 0);  // function(conn)
}
int lua_Technique_getPass(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, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL))
            {
                // Get parameter 1 off the stack.
                const char* param1 = gameplay::ScriptUtil::getString(2, false);

                Technique* instance = getInstance(state);
                void* returnPtr = ((void*)instance->getPass(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, "Pass");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_Technique_getPass - 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;
}
Beispiel #17
0
// Lua: s = net.create(type, secure/timeout, function(conn))
static int net_create( lua_State* L, const char* mt )
{
  NODE_DBG("net_create is called.\n");
  struct espconn *pesp_conn = NULL;
  lnet_userdata *nud, *temp = NULL;
  unsigned type;
#ifdef CLIENT_SSL_ENABLE
  unsigned secure = 0;
#endif
  uint8_t stack = 1;
  bool isserver = false;
  
  if (mt!=NULL && c_strcmp(mt, "net.server")==0)
    isserver = true;
  else if (mt!=NULL && c_strcmp(mt, "net.socket")==0)
    isserver = false;
  else
  {
    NODE_DBG("wrong metatable for net_create.\n");
    return 0;
  }

  type = luaL_checkinteger( L, stack );
  if ( type != ESPCONN_TCP && type != ESPCONN_UDP )
    return luaL_error( L, "wrong arg type" );
  stack++;
#ifdef CLIENT_SSL_ENABLE
  if(!isserver){
    if ( lua_isnumber(L, stack) )
    {
      secure = lua_tointeger(L, stack);
      stack++;
      if ( secure != 0 && secure != 1 ){
        return luaL_error( L, "wrong arg type" );
      }
    } else {
      secure = 0; // default to 0
    }
  }
#endif

  if(isserver && type == ESPCONN_TCP){
    if ( lua_isnumber(L, stack) )
    {
      unsigned to = lua_tointeger(L, stack);
      stack++;
      if ( to < 1 || to > 28800 ){
        return luaL_error( L, "wrong arg type" );
      }
      tcp_server_timeover = (uint16_t)to;
    } else {
      tcp_server_timeover = 30; // default to 30
    }
  }

  // create a object
  nud = (lnet_userdata *)lua_newuserdata(L, sizeof(lnet_userdata));
  // pre-initialize it, in case of errors
  nud->self_ref = LUA_NOREF;
  nud->cb_connect_ref = LUA_NOREF;
  nud->cb_reconnect_ref = LUA_NOREF;
  nud->cb_disconnect_ref = LUA_NOREF;
  nud->cb_receive_ref = LUA_NOREF;
  nud->cb_send_ref = LUA_NOREF;
  nud->cb_dns_found_ref = LUA_NOREF;
  nud->pesp_conn = NULL;
#ifdef CLIENT_SSL_ENABLE
  nud->secure = secure;
#endif

  // set its metatable
  luaL_getmetatable(L, mt);
  lua_setmetatable(L, -2);

  // create the espconn struct
  if(isserver && type==ESPCONN_TCP && pTcpServer){
    if(tcpserver_cb_connect_ref != LUA_NOREF){      // self_ref should be unref in close()
      lua_pop(L,1);
      return luaL_error(L, "only one tcp server allowed");
    }
    pesp_conn = nud->pesp_conn = pTcpServer;
  } else if(isserver && type==ESPCONN_UDP && pUdpServer){
    temp = (lnet_userdata *)pUdpServer->reverse;
    if(temp && temp->self_ref != LUA_NOREF){
      lua_pop(L,1);
      return luaL_error(L, "only one udp server allowed");
    }
    pesp_conn = nud->pesp_conn = pUdpServer;
  } else {
    pesp_conn = nud->pesp_conn = (struct espconn *)c_zalloc(sizeof(struct espconn));
    if(!pesp_conn)
      return luaL_error(L, "not enough memory");

    pesp_conn->proto.tcp = NULL;
    pesp_conn->proto.udp = NULL;
    pesp_conn->reverse = NULL;
    if( type==ESPCONN_TCP )
    {
      pesp_conn->proto.tcp = (esp_tcp *)c_zalloc(sizeof(esp_tcp));
      if(!pesp_conn->proto.tcp){
        c_free(pesp_conn);
        pesp_conn = nud->pesp_conn = NULL;
        return luaL_error(L, "not enough memory");
      }
      NODE_DBG("TCP server/socket is set.\n");
    }
    else if( type==ESPCONN_UDP )
    {
      pesp_conn->proto.udp = (esp_udp *)c_zalloc(sizeof(esp_udp));
      if(!pesp_conn->proto.udp){
        c_free(pesp_conn);
        pesp_conn = nud->pesp_conn = NULL;
        return luaL_error(L, "not enough memory");
      }
      NODE_DBG("UDP server/socket is set.\n");
    }
  }
  pesp_conn->type = type;
  pesp_conn->state = ESPCONN_NONE;
  // reverse is for the callback function
  pesp_conn->reverse = nud;

  if(isserver && type==ESPCONN_TCP && pTcpServer==NULL){
    pTcpServer = pesp_conn;
  } else if(isserver && type==ESPCONN_UDP && pUdpServer==NULL){
    pUdpServer = pesp_conn;
  }

  gL = L;   // global L for net module.

  // if call back function is specified, call it with para userdata
  // luaL_checkanyfunction(L, 2);
  if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){
    lua_pushvalue(L, stack);  // copy argument (func) to the top of stack
    lua_pushvalue(L, -2);  // copy the self_ref(userdata) to the top
    lua_call(L, 1, 0);
  }

  return 1; 
}
Beispiel #18
0
/*
 * rspamd_dispatcher.create(base,fd, read_cb, write_cb, err_cb[, timeout])
 */
static int
lua_io_dispatcher_create (lua_State *L)
{
	struct rspamd_io_dispatcher_s *io_dispatcher, **pdispatcher;
	gint fd;
	struct lua_dispatcher_cbdata *cbdata;
	struct timeval tv = {0, 0};
	double tv_num, tmp;

	if (lua_gettop (L) >= 5 && lua_isfunction (L, 3) && lua_isfunction (L, 5)) {
		cbdata = g_slice_alloc0 (sizeof (struct lua_dispatcher_cbdata));
		cbdata->base = lua_check_event_base (L);
		if (cbdata->base == NULL) {
			/* Create new event base */
			msg_warn ("create new event base as it is not specified");
			cbdata->base = event_init ();
		}
		cbdata->L = L;
		fd = lua_tointeger (L, 2);
		lua_pushvalue (L, 3);
		cbdata->cbref_read = luaL_ref (L, LUA_REGISTRYINDEX);
		if (lua_isfunction (L, 4)) {
			/* Push write callback as well */
			lua_pushvalue (L, 4);
			cbdata->cbref_write = luaL_ref (L, LUA_REGISTRYINDEX);
		}
		/* Error callback */
		lua_pushvalue (L, 5);
		cbdata->cbref_err = luaL_ref (L, LUA_REGISTRYINDEX);

		if (lua_gettop (L) > 5) {
			tv_num = lua_tonumber (L, 6);
			tv.tv_sec = trunc (tv_num);
			tv.tv_usec = modf (tv_num, &tmp) * 1000.;
			io_dispatcher = rspamd_create_dispatcher (cbdata->base,
					fd,
					BUFFER_LINE,
					lua_io_read_cb,
					lua_io_write_cb,
					lua_io_err_cb,
					&tv,
					cbdata);
		}
		else {
			io_dispatcher = rspamd_create_dispatcher (cbdata->base,
					fd,
					BUFFER_LINE,
					lua_io_read_cb,
					lua_io_write_cb,
					lua_io_err_cb,
					NULL,
					cbdata);
		}

		cbdata->d = io_dispatcher;
		/* Push result */
		pdispatcher =
			lua_newuserdata (L, sizeof (struct rspamd_io_dispatcher_s *));
		rspamd_lua_setclass (L, "rspamd{io_dispatcher}", -1);
		*pdispatcher = io_dispatcher;
	}
	else {
		msg_err ("invalid number of arguments to io_dispatcher.create: %d",
			lua_gettop (L));
		lua_pushnil (L);
	}

	return 1;
}
Beispiel #19
0
void ExeciteAspPage(lua_State *L, const char *asp_page,
        const struct AspPageContext *context)
{
    void *compiled_page = NULL;
    int result;
    char *error_message = NULL;
    struct AspliteCallbackUserdata *udata;

    int stack = lua_gettop(L);

    luaL_openlibs(L);

    luaopen_asplite(L);

    // create and populate 'context' table
    lua_pushstring(L, "context");
    lua_newtable(L);

    lua_pushstring(L, "write_func");
    udata = lua_newuserdata(L, sizeof(struct AspliteCallbackUserdata));
    udata->context = context;
    udata->write_func = context->write_func;
    lua_pushcclosure(L, WriteCallbackWrapper, 1);
    lua_settable(L, -3);

    lua_pushstring(L, "error_func");
    udata = lua_newuserdata(L, sizeof(struct AspliteCallbackUserdata));
    udata->context = context;
    udata->write_func = context->error_func;
    lua_pushcclosure(L, WriteCallbackWrapper, 1);
    lua_settable(L, -3);

    lua_pushstring(L, "log_func");
    udata = lua_newuserdata(L, sizeof(struct AspliteCallbackUserdata));
    udata->context = context;
    udata->write_func = context->log_func;
    lua_pushcclosure(L, WriteCallbackWrapper, 1);
    lua_settable(L, -3);

    // create request table
    lua_pushstring(L, "request");
    lua_newtable(L);

    lua_pushstring(L, "QUERY_STRING");
    lua_pushstring(L, context->request.query_string);
    lua_settable(L, -3);

    lua_pushstring(L, "HTTP_METHOD");
    lua_pushstring(L, context->request.request_method);
    lua_settable(L, -3);
    lua_pushstring(L, "REQUEST_METHOD");
    lua_pushstring(L, context->request.request_method);
    lua_settable(L, -3);

    // set context.request field
    lua_settable(L, -3);

    // set asplite.context field
    lua_settable(L, -3);

    lua_pop(L, 1); // pop asplite table

    result = CompileAspPage(L, asp_page, &context->engine_config, &error_message);
    if (result) {
        udata = lua_newuserdata(L, sizeof(struct AspliteCallbackUserdata));
        udata->context = context;
        udata->write_func = context->error_func;
        lua_pushcclosure(L, WriteCallbackWrapper, 1);
        lua_pushstring(L, error_message);
        lua_call(L, 1, 0);
        free(error_message);
        assert(stack == lua_gettop(L));
        return;
    }

#ifdef USE_EMBEDDED_DRIVER
    result = luaL_loadbufferx(L, asplite_Driver, sizeof(asplite_Driver),
            "asplite_Driver", NULL);
#else
    result = luaL_loadfile(L, "asplite.lua");
#endif // USE_EMBEDDED_DRIVER
    if (result == LUA_OK) {
        result = lua_pcall(L, 0, 0, 0);
    }

    if (result != LUA_OK) {
        udata = lua_newuserdata(L, sizeof(struct AspliteCallbackUserdata));
        udata->context = context;
        udata->write_func = context->error_func;
        lua_pushcclosure(L, WriteCallbackWrapper, 1);
        lua_pushvalue(L, -2);
        lua_call(L, 1, 0);
    }

    assert(stack == lua_gettop(L));

    return;
}
LUA_API void lua_pushvmatrix (lua_State *L, lua_VMatrix &matrix) {
  lua_VMatrix *pMat = (lua_VMatrix *)lua_newuserdata(L, sizeof(lua_VMatrix));
  *pMat = matrix;
  luaL_getmetatable(L, "VMatrix");
  lua_setmetatable(L, -2);
}
Beispiel #21
0
TMODENTRY int luaopen_tek_lib_exec(lua_State *L)
{
	struct TExecBase *TExecBase;
	struct LuaExecTask *lexec;
	TTAGITEM tags[2];
	
	luaL_newmetatable(L, TEK_LIB_EXEC_CLASSNAME);
	tek_lua_register(L, NULL, tek_lib_exec_methods, 0);
	/* execmeta */

#if defined(ENABLE_TASKS)
	luaL_newmetatable(L, TEK_LIB_TASK_CLASSNAME);
	/* execmeta, taskmeta */
	lua_pushvalue(L, -2);
	/* execmeta, taskmeta, execmeta */
	tek_lua_register(L, NULL, tek_lib_exec_child_methods, 1);
	lua_pushvalue(L, -1);
	/* execmeta, taskmeta, taskmeta */
	lua_setfield(L, -2, "__index");
	lua_pop(L, 1);
	/* execmeta */
#endif
	
	lexec = (struct LuaExecTask *)lua_newuserdata(L, sizeof(struct LuaExecTask));
	/* execmeta, luaexec */
	lexec->exec = TNULL;
	
	lua_pushvalue(L, -1);
	/* execmeta, luaexec, luaexec */
	lua_pushvalue(L, -3);
	/* execmeta, luaexec, luaexec, execmeta */
	tek_lua_register(L, "tek.lib.exec", tek_lib_exec_funcs, 2);
	/* execmeta, luaexec, libtab */

	lua_pushvalue(L, -2);
	/* execmeta, luaexec, libtab, libtab */
	lua_pushvalue(L, -4);
	/* execmeta, luaexec, libtab, libtab, execmeta */
	lua_remove(L, -4);
	lua_remove(L, -4);
	/* libtab, libtab, execmeta */

	lua_setmetatable(L, -2);
	/* libtab, libtab */
	lua_setfield(L, -2, "base");
	/* libtab */

	tags[0].tti_Tag = TExecBase_ModInit;
	tags[0].tti_Value = (TTAG) tek_lib_exec_initmodules;
	tags[1].tti_Tag = TTAG_DONE;

	lexec->task = TEKCreate(tags);
	if (lexec->task == TNULL)
		luaL_error(L, "Failed to initialize TEKlib");
	lexec->exec = TExecBase = (struct TExecBase *)TGetExecBase(lexec->task);

#if defined(ENABLE_TASKS)
	if (!tek_lib_exec_init_link_to_parent(L, lexec))
	{
		lua_pop(L, 1);
		return 0;
	}
#endif

	return 1;
}
Beispiel #22
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);
}
Beispiel #23
0
/**
 * Push a new Lua proxy object (struct object) onto the Lua stack.  It gets an
 * entry in the aliases table (unless it is a stack object); the caller must
 * take care of an entry in the objects table.
 *
 * @param p  pointer to the object to make the Lua object for; must not be NULL.
 * @param ts  what the pointer type is; 0 for auto detect
 * @param flags  see lg_get_object
 * @return  -1 on error (nothing pushed), NULL (stack object) or >0 (normal)
 *
 * Lua stack: unless -1 is returned, a new object is pushed.
 */
static struct object *_make_object(lua_State *L, void *p, typespec_t ts,
    int flags)
{
    struct object *o;

    // 0 is valid - for autodetection.  == module_count is OK as it is 1 based.
    if (ts.module_idx > module_count) {
	luaL_error(L, "%s invalid module_idx %d in _make_object",
	    msgprefix, ts.module_idx);
	return (void*) -1;
    }

    /* If the structure number is not given, the object must be derived from
     * GObject; otherwise, the result is undefined (probably SEGV). */
    if (!ts.type_idx) {
	ts = _determine_object_type(L, p);
	if (!ts.value)
	    return (void*) -1;
    }

    if (ts.type_idx <= 0 || ts.type_idx >= modules[ts.module_idx]->type_count) {
	luaL_error(L, "%s invalid type_idx %d in _make_object",
	    msgprefix, ts.type_idx);
	return (void*) -1;
    }

    /* make new Lua object with meta table */
    o = (struct object*) lua_newuserdata(L, sizeof(*o));
    memset(o, 0, sizeof(*o));
    o->p = p;
    o->ts = ts;
    o->is_new = 1;

    /* determine which object type to use. */
    lg_guess_object_type(L, o, flags);

    /* set metatable - shared among objects of the same type */
    _get_object_meta(L, ts);			// o meta
    lua_setmetatable(L, -2);			// o

    /* Set the environment to an empty table - used to store data with
     * arbitrary keys for a specific object.  The env can't be nil.  To avoid
     * having an unused table for each object, use the same for all and replace
     * with a private table when the first data is stored.
     */
    lua_getglobal(L, LUAGNOME_TBL);		// o gnome
    lua_getfield(L, -1, LUAGNOME_EMPTYATTR);	// o gnome emptyattr
    lua_setfenv(L, -3);				// o gnome

    // Increase refcount (but not always - see ffi2lua_struct_ptr).  flags
    // may have FLAG_NEW_OBJECT set.
    lg_inc_refcount(L, o, flags);

    // Stack objects neither get an entry in gnome.objects, nor in
    // gnome.aliases.  They can't be reused anyway.
    if (_is_on_stack(p)) {
	lua_pop(L, 1);				// o
	return NULL;
    }

    // Store the new object in the aliases table, using its own address
    // as a key.
    lua_getfield(L, -1, LUAGNOME_ALIASES);	// o gnome aliases
    lua_pushlightuserdata(L, o);		// o gnome aliases *o
    lua_pushvalue(L, -4);			// o gnome aliases *o o
    lua_rawset(L, -3);				// o gnome aliases
    lua_pop(L, 2);				// o

    return o;
}
Beispiel #24
0
static int lua_Pass_getParameterByIndex(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, 2) == LUA_TNUMBER)
            {
                // Get parameter 1 off the stack.
                unsigned int param1 = (unsigned int)luaL_checkunsigned(state, 2);

                Pass* instance = getInstance(state);
                void* returnPtr = ((void*)instance->getParameterByIndex(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, "MaterialParameter");
                    lua_setmetatable(state, -2);
                }
                else
                {
                    lua_pushnil(state);
                }

                return 1;
            }

            lua_pushstring(state, "lua_Pass_getParameterByIndex - 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;
}
Beispiel #25
0
int lua_Model_setMaterial(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:
        {
            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    (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;
                    gameplay::ScriptUtil::LuaArray<Material> param1 = gameplay::ScriptUtil::getObjectPointer<Material>(2, "Material", false, &param1Valid);
                    if (!param1Valid)
                        break;

                    Model* instance = getInstance(state);
                    instance->setMaterial(param1);
                    
                    return 0;
                }
            } while (0);

            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);

                    Model* instance = getInstance(state);
                    void* returnPtr = ((void*)instance->setMaterial(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;
                }
            } while (0);

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

                    // Get parameter 2 off the stack.
                    int param2 = (int)luaL_checkint(state, 3);

                    Model* instance = getInstance(state);
                    instance->setMaterial(param1, param2);
                    
                    return 0;
                }
            } while (0);

            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    (lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
                    (lua_type(state, 3) == LUA_TSTRING || lua_type(state, 3) == LUA_TNIL))
                {
                    // Get parameter 1 off the stack.
                    const char* param1 = gameplay::ScriptUtil::getString(2, false);

                    // Get parameter 2 off the stack.
                    const char* param2 = gameplay::ScriptUtil::getString(3, false);

                    Model* instance = getInstance(state);
                    void* returnPtr = ((void*)instance->setMaterial(param1, param2));
                    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;
                }
            } while (0);

            do
            {
                if ((lua_type(state, 1) == LUA_TUSERDATA) &&
                    (lua_type(state, 2) == LUA_TSTRING || lua_type(state, 2) == LUA_TNIL) &&
                    lua_type(state, 3) == LUA_TNUMBER)
                {
                    // Get parameter 1 off the stack.
                    const char* param1 = gameplay::ScriptUtil::getString(2, false);

                    // Get parameter 2 off the stack.
                    int param2 = (int)luaL_checkint(state, 3);

                    Model* instance = getInstance(state);
                    void* returnPtr = ((void*)instance->setMaterial(param1, param2));
                    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;
                }
            } while (0);

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

                    // Get parameter 2 off the stack.
                    const char* param2 = gameplay::ScriptUtil::getString(3, false);

                    // Get parameter 3 off the stack.
                    const char* param3 = gameplay::ScriptUtil::getString(4, false);

                    Model* instance = getInstance(state);
                    void* returnPtr = ((void*)instance->setMaterial(param1, param2, param3));
                    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;
                }
            } while (0);

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

                    // Get parameter 2 off the stack.
                    const char* param2 = gameplay::ScriptUtil::getString(3, false);

                    // Get parameter 3 off the stack.
                    const char* param3 = gameplay::ScriptUtil::getString(4, false);

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

                    Model* instance = getInstance(state);
                    void* returnPtr = ((void*)instance->setMaterial(param1, param2, param3, param4));
                    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;
                }
            } while (0);

            lua_pushstring(state, "lua_Model_setMaterial - 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, 3, 4 or 5).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Beispiel #26
0
static int lua_FontGlyph__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 Font::Glyph());
            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, "FontGlyph");
                lua_setmetatable(state, -2);
            }
            else
            {
                lua_pushnil(state);
            }

            return 1;
            break;
        }
        default:
        {
            lua_pushstring(state, "Invalid number of parameters (expected 0).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Beispiel #27
0
static int
config_env_os_execute(lua_State *L)
{
    if(lua_type(L, 1) == LUA_TTABLE) {
        struct execute_options options;

        memset(&options, 0, sizeof(struct execute_options));

        process_options(L, &options);

        pid_t pid;

        pid = fork();

        if(pid == -1) {
            lua_pushnil(L);
            lua_pushstring(L, strerror(errno));
            lua_pushinteger(L, errno);

            return 3;
        } else {
            if(pid) {
                int status;

                if(options.stdout_handle) {
                    fclose(options.stdout_handle);
                }

                if(options.stderr_handle) {
                    fclose(options.stderr_handle);
                }

                waitpid(pid, &status, 0);

                if(status) {
                    lua_pushnil(L);
                    lua_pushliteral(L, "execution failed");
                    lua_pushinteger(L, status);

                    return 3;
                } else {
                    lua_pushboolean(L, 1);
                    return 1;
                }
            } else {
                char **argv;
                int nargs;
                int i;

                if(options.stdout_handle) {
                    dup2(fileno(options.stdout_handle), fileno(stdout));
                }

                if(options.stderr_handle) {
                    dup2(fileno(options.stderr_handle), fileno(stderr));
                }

                nargs = lua_objlen(L, 1);
                argv  = lua_newuserdata(L, sizeof(char *) * (nargs + 1));

                for(i = 1; i <= nargs; i++) {
                    const char *arg;

                    lua_rawgeti(L, 1, i);
                    arg         = luaL_checkstring(L, -1);
                    argv[i - 1] = arg; /* we don't need to make a copy, since
                                        * we're keeping the table on the stack
                                        */
                    lua_pop(L, 1);
                }
                argv[nargs] = NULL;

                execvp(argv[0], argv);
                exit(255); /* this should never be reached */
            }
        }
    } else {
        lua_pushvalue(L, lua_upvalueindex(1));
        lua_insert(L, 1);
        lua_call(L, lua_gettop(L) - 1, LUA_MULTRET);

        return lua_gettop(L);
    }
}
Beispiel #28
0
static int pb_port_cb_packet(int portfd, int linefd, int bodyfd){

    Port *port = port_from_fd(portfd);
    Line *line = line_from_fd(linefd);
    if(port == NULL){
        LOG_ERROR("port is null");
        return 0;
    }
    if(line == NULL){
        LOG_ERROR("line is null");
        return 0;
    }
    char *body = ar_ptr(bodyfd);
    int body_len = ar_remain(bodyfd);

    int plen = *(int *)body + 4;
    body += sizeof(int);
    body_len -= sizeof(int);

    int msg_name_len = *(unsigned short *)body;
    body += sizeof(unsigned short);
    body_len -= sizeof(unsigned short);
    if(msg_name_len >= MAX_MSG_NAME_LEN - 1){
        LOG_ERROR("reach max msg name len %d/%d", msg_name_len, MAX_MSG_NAME_LEN);
        return 0;
    }
    memcpy(recv_msg_name, body, msg_name_len);
    recv_msg_name[msg_name_len] = 0;
    XOR(recv_msg_name, msg_name_len);

    body += msg_name_len;
    body_len -= msg_name_len;

    int seq = *(int *)body;
    body += sizeof(int);
    body_len -= sizeof(int);

    lua_State *L = luas_open();
    const char *func = port->lua_cb_packet;

    line->recv_seq = 4 * line->recv_seq + 9;
    if(line->uid != 0 && line->recv_seq != seq){
        LOG_ERROR("seq error expected %d recv %d", line->recv_seq, seq);
    }else if(func[0] != 0){
        struct timeval t1;
        gettimeofday(&t1, NULL);

        google::protobuf::Message* message = pbc_load_msg(recv_msg_name);
        if(message == NULL){
            LOG_ERROR("can not load %d msg %s", msg_name_len, recv_msg_name);
            return 0;
        }
        google::protobuf::io::ArrayInputStream stream(body, body_len);
        if(message->ParseFromZeroCopyStream(&stream) == 0){
            delete message;
            LOG_ERROR("parse fail\n");
            return 0;
        }

        LOG_MSG("[%d]RECV %s plen:%d FROM %s", line->uid, recv_msg_name, plen, port->name);

        if(message->ByteSize() < 4096){
            LOG_DEBUG("%s", message->DebugString().data());
        }

        luas_pushluafunction(func);
        //sock 
        lua_pushnumber(L, linefd);
        //cmd
        lua_pushstring(L, recv_msg_name);
        //msg
        LuaMessage *message_lua = (LuaMessage *)lua_newuserdata(L, sizeof(LuaMessage));
        if(message_lua == NULL){
            lua_pop(L, lua_gettop(L));
            delete message;
            LOG_ERROR("newuserdata null %s", recv_msg_name);
            return 0;
        }
        message_lua->message = message;
        message_lua->root_message = message_lua;
        message_lua->dirty = 0;
        luaL_getmetatable(L, "LuaMessage");
        lua_setmetatable(L, -2);
        int args_num = 3;
        if (lua_pcall(L, args_num, 1, 0) != 0){
            LOG_ERROR("error running function %s: %s", func, lua_tostring(L, -1));
        }
        struct timeval t2;
        gettimeofday(&t2, NULL);
        LOG_MSG("[%d]RECV_END %s usec:%d FROM %s", line->uid, recv_msg_name, time_diff(&t1, &t2), port->name);
        lua_pop(L, lua_gettop(L));

    }
    return 1;
}
int lua_PhysicsCollisionShapeDefinition__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 PhysicsCollisionShape::Definition();
            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, "PhysicsCollisionShapeDefinition");
                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<PhysicsCollisionShape::Definition> param1 = gameplay::ScriptUtil::getObjectPointer<PhysicsCollisionShape::Definition>(1, "PhysicsCollisionShapeDefinition", true, &param1Valid);
                    if (!param1Valid)
                        break;

                    void* returnPtr = (void*)new PhysicsCollisionShape::Definition(*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, "PhysicsCollisionShapeDefinition");
                        lua_setmetatable(state, -2);
                    }
                    else
                    {
                        lua_pushnil(state);
                    }

                    return 1;
                }
            } while (0);

            lua_pushstring(state, "lua_PhysicsCollisionShapeDefinition__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 1).");
            lua_error(state);
            break;
        }
    }
    return 0;
}
Beispiel #30
0
int addon_output_init(struct output *o) {

	struct addon *addon = o->info->reg_info->mod->priv;

	lua_State *L = addon_create_state(addon->filename); // Stack : empty

	if (!L) {
		pomlog(POMLOG_ERR "Error while creating new lua state for output %s", o->info->reg_info->name);
		return POM_ERR;
	}

	// Get the output from the outputs table
	lua_getfield(L, LUA_REGISTRYINDEX, ADDON_OUTPUTS_TABLE); // Stack : outputs
	lua_getfield(L, -1, o->info->reg_info->name); // Stack : outputs, output

	// Get rid of the outputs table
	lua_remove(L, -2); // Stack : output
	lua_pushnil(L); // Stack : output, nil
	lua_setfield(L, LUA_REGISTRYINDEX, ADDON_OUTPUTS_TABLE); // Stack : output

	// Add the output to the registry
	lua_pushvalue(L, -1); // Stack : output, output
	lua_setfield(L, LUA_REGISTRYINDEX, ADDON_INSTANCE); // Stack : output


	// Create the private data
	// TODO make __priv read-only
	struct addon_instance_priv *p = lua_newuserdata(L, sizeof(struct addon_instance_priv)); // Stack : output, priv
	if (!p) {
		pom_oom(sizeof(struct addon_instance_priv));
		return POM_ERR;
	}
	memset(p, 0, sizeof(struct addon_instance_priv));
	o->priv = p;
	p->instance = o;
	p->L = L;
	if (pthread_mutex_init(&p->lock, NULL)) {
		pomlog(POMLOG_ERR "Error while initializing mutex : %s", pom_strerror(errno));
		abort();
		return POM_ERR;
	}

	// Assign the output_priv metatable
	luaL_getmetatable(L, ADDON_OUTPUT_PRIV_METATABLE); // Stack : output, priv, metatable
	lua_setmetatable(L, -2); // Stack : output, priv
	// Add it to __priv
	lua_setfield(L, -2, "__priv"); // Stack : output

	// Fetch the parameters table 
	lua_getfield(L, -1, "__params"); // Stack : output, params

	// Parse each param from the class
	lua_pushnil(L); // Stack : output, params, nil
	while (lua_next(L, -2) != 0) { // Stack : output, params, key, param
		if (!lua_istable(L, -1)) {
			pomlog(POMLOG_ERR "Parameters should be described in tables");
			goto err;
		}

		// Fetch the name
		lua_pushinteger(L, 1); // Stack : output, params, key, param, 1
		lua_gettable(L, -2); // Stack : output, params, key, param, name
		if (!lua_isstring(L, -1)) {
			pomlog(POMLOG_ERR "Parameter name is not a string");
			goto err;
		}
		const char *name = luaL_checkstring(L, -1);
		lua_pop(L, 1); // Stack : output, params, key, param

		// Fetch the ptype type
		lua_pushinteger(L, 2); // Stack : output, params, key, param, 2
		lua_gettable(L, -2); // Stack : output, params, key, param, type
		if (!lua_isstring(L, -1)) {
			pomlog(POMLOG_ERR "Parameter type is not a string");
			goto err;
		}
		const char *type = lua_tostring(L, -1);
		lua_pop(L, 1); // Stack : output, params, key, param

		// Fetch the default value
		lua_pushinteger(L, 3); // Stack : output, params, key, param, 3
		lua_gettable(L, -2); // Stack : output, params, key, param, defval
		if (!lua_isstring(L, -1)) {
			pomlog(POMLOG_ERR "Parameter default value is not a string");
			goto err;
		}
		const char *defval = lua_tostring(L, -1);
		lua_pop(L, 1); // Stack : output, params, key, param

		// Fetch the description
		lua_pushinteger(L, 4); // Stack : output, params, key, param, 4
		lua_gettable(L, -2); // Stack : output, params, key, param, descr
		if (!lua_isstring(L, -1)) {
			pomlog(POMLOG_ERR "Parameter description is not a string");
			goto err;
		}
		const char *descr = lua_tostring(L, -1);
		lua_pop(L, 1); // Stack : output, params, key, param

		// Allocate it
		struct addon_param *param = malloc(sizeof(struct addon_param));
		if (!param) {
			pom_oom(sizeof(struct addon_param));
			goto err;
		}
		param->name = strdup(name);
		if (!param->name) {
			free(param);
			pom_oom(strlen(name) + 1);
			goto err;
		}
		param->value = ptype_alloc(type);
		if (!param->value) {
			free(param->name);
			free(param);
			goto err;
		}
		
		struct registry_param *reg_param = registry_new_param((char*)name, (char*)defval, param->value, (char*)descr, 0);
		if (output_add_param(o, reg_param) != POM_OK) {
			pomlog(POMLOG_ERR "Error while adding parameter to the output instance");
			if (reg_param)
				registry_cleanup_param(reg_param);
			free(param->name);
			ptype_cleanup(param->value);
			free(param);
			goto err;
		}

		param->next = p->params;
		p->params = param;


		// Pop the value (the param table)
		lua_pop(L, 1); // Stack : output, params, key
	}
	// At this point the stack is : output, params
	lua_pop(L, 2); // Stack : empty

	pomlog(POMLOG_DEBUG "Output %s created", o->name);
	return POM_OK;

err:
	lua_close(L);
	p->L = NULL;
	return POM_ERR;
}