Lua中的string.byte函数能否返回负值?

我正在调试别人的代码。我不太懂Lua。我想知道从string.byte返回负值是否可能。

原文链接 https://stackoverflow.com/questions/4556942

点赞
stackoverflow用户557445
stackoverflow用户557445

将下面翻译成中文并且保留原本的 markdown 格式

It doesn't appear that it can return negative values - however I haven't worked with it much.

它似乎不能返回负值 —— 但我并没有多少使用经验。

以下是一些可能有用的文档链接:

2010-12-29 19:00:42
stackoverflow用户556994
stackoverflow用户556994

不行。string.byte() 的范围应该是 0..255 包括在内; 文档没有指定,但源代码很清楚:

static int str_byte(lua_State*L){
  size_t l;
  const char*s=luaL_checklstring(L,1,&l);
  ptrdiff_t posi=posrelat(luaL_optinteger(L,2,1),l);
  ptrdiff_t pose=posrelat(luaL_optinteger(L,3,posi),l);
  int n,i;
  if(posi<=0)posi=1;
  if((size_t)pose>l)pose=l;
  if(posi>pose)return0;/*空间间隔;不返回值*/
  n=(int)(pose-posi+1);
  if(posi+n<=pose)/*溢出?*/
    luaL_error(L,"字符串切片太长");
  luaL_checkstack(L,n,"字符串切片太长");
  for(i=0;i<n;i++)
    lua_pushinteger(L,uchar(s[posi+i-1]));
  return n;
}

来自[lua-5.1.4/src/strlib.c](http://www.lua.org/source/5.1/lstrlib.c.html#str_byte),(C)1994-2008 Lua.org;根据BSD许可证

重要的一行是对 lua_pushinteger 的调用,它用于将整数值返回给调用函数,而 uchar 则将值协作到 0..255 的范围内。

2010-12-29 19:01:48
stackoverflow用户459706
stackoverflow用户459706

如果你对 Lua 的内部运作有任何问题,最简单的方法就是查看源代码:http://www.lua.org/source/5.1/lstrlib.c.html#str_byte(是的,我知道理解这个需要一些工作;)

2010-12-30 09:49:10