slua
slua copied to clipboard
fix lua_tostring gc
从 https://github.com/lua/lua/blob/v5-3-0/lgc.c#L690-L692代码上来看,短字符串也是会被回收的,没有仔细看代码修改,万望勿怪.
lua 短字符会被 intern到state 中一个叫strt.hash 的哈希表中, https://github.com/lua/lua/blob/3c55790ebee7148281cd00f44aa293e456b4da6d/lstring.c#L153
而这个hash表目测只有在 state_close的时候才会被调用 https://github.com/lua/lua/blob/6b01b6cf6a1631f7ca2ce527a5c355517095c209/lstate.c#L266
不过这里有个判断是否这个字符串已经被GC,感觉应该是缓存机制吧 https://github.com/lua/lua/blob/3c55790ebee7148281cd00f44aa293e456b4da6d/lstring.c#L131
我写了一段测试代码(lua5.3.4):
#include <stdint.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
static int
lget(lua_State *L)
{
lua_pushinteger(L, (intptr_t)lua_tostring(L, -1));
return 1;
}
static const luaL_Reg ptr[] = {
{"get", lget},
{NULL, NULL}
};
LUAMOD_API int luaopen_ptr(lua_State *L) {
luaL_newlib(L, ptr);
return 1;
}
local ptr = require "ptr"
--test
local a = 1 .. ":"
print(string.format("0x%x", ptr.get(a)))
a = nil
input = nil
collectgarbage()
a = 1 .. ":"
print(string.format("0x%x", ptr.get(a)))
结果是
0x24c3ab8
0x24c6c18