3

loadbuffer を使用して 2 つの文字列を 1 つの lua_state にロードします。

if( luaL_loadbuffer( L, str.c_str(), str.size(), "line") != 0 )
{
    printf( "%s\n", lua_tostring ((lua_State *)L, -1));
}
lua_pcall(L, 0, 0, 0);

if( luaL_loadbuffer( L, str2.c_str(), str2.size(), "line2") != 0 )
{
    printf( "%s\n", lua_tostring ((lua_State *)L, -1));
}
lua_pcall(L, 0, 0, 0);

例えば:

function f ()


    print( "Hello World!")
end

function g ()

    f(
end

2 番目の文字列のForgetable)はエラーをスローします。

[string "line2"]:9: unexpected Symbol

ただし、9はストリング 1 とストリング 2 の行番号です。行番号は 3 のはずです。

loadbuffer を呼び出す前に行番号カウンターをリセットする方法はありますか?

4

3 に答える 3

1

このリンクはあなたの状況を説明していると思います: http://www.corsix.org/content/common-lua-pitfall-loading-code

情報の 2 つのチャンクをロードしています。チャンクを呼び出すと、グローバル テーブルに連続して配置されます。はandlua_pcall(L, 0, 0, 0);を呼び出していませんが、lua コードを順次構築しています。f()g()

コードは次のように簡略化できます。

if (luaL_dostring(L, str.c_str()))
{
    printf("%s\n", lua_tostring (L, -1));
}
if (luaL_dostring(L, str2.c_str()));
{
    printf("%s\n", lua_tostring (L, -1));
}

また、ロードに失敗したときにチャンクを呼び出すことから保護します。

于 2013-06-07T09:35:29.963 に答える
0

誰かがそれを必要とするなら。

この関数を lauxlib.h に追加します。

LUALIB_API int (luaL_loadbuffers) (lua_State *L, size_t count, const char **buff, size_t *sz,
                                   const char **name, const char *mode);

そしてlauxlib.cへ

#include"lzio.h"
#include"ldo.h"
#include"ltable.h"
#include"lgc.h"
LUALIB_API int luaL_loadbuffers (lua_State *L, size_t count, const char **buff, size_t *sz,
                                   const char **name, const char *mode)
{
    ZIO z;
    int status;

    int i;

    for( i=0; i<count; i++)
    {
        LoadS ls;
        ls.s = buff[i];
        ls.size = sz[i];

        lua_lock(L);

        luaZ_init(L, &z, getS, &ls);
        status = luaD_protectedparser(L, &z, name[i], mode);

        if (status == LUA_OK) {  /* no errors? */
            LClosure *f = clLvalue(L->top - 1);  /* get newly created function */
            if (f->nupvalues == 1) {  /* does it have one upvalue? */

                /* get global table from registry */
                Table *reg = hvalue(&G(L)->l_registry);
                const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
                /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
                setobj(L, f->upvals[0]->v, gt);
                luaC_barrier(L, f->upvals[0], gt);


            } // == 1

            lua_pcall( L, 0, 0, 0);
        }

        lua_unlock(L);

        if( status != LUA_OK )
            break;
    }

    return status;
}

すべての文字列/ファイルには、独自の行番号が付けられます。これは、ほとんど、lapi.c の lua_load のコピーにすぎません。LUA の新しいリリースでは、調整がとても簡単です。

于 2013-06-08T16:48:20.503 に答える