Lua Locales

lua-users home
wiki

这里有一些关于 Lua 中 [locales] 的说明。

Lua 深受标准 C 的影响,因此 C 处理 locale 的很多方面都适用于 Lua。

当前的 locale 可以使用 [os.setlocale] 函数获取或设置。

警告:os.setlocale 内部会调用 C 的 [setlocale] 函数,该函数会全局设置当前进程中所有 Lua 状态和所有 OS 线程的 locale。但是,某些 C 实现提供了非标准的函数(例如 Microsoft 的 [_configthreadlocale]),这样只会影响当前的 OS 线程。

关于 Lua 中 locale 的简要背景介绍 [PiL 22.2](警告:请参阅下面的历史说明)。

Lua 语法

在 Lua 5.1 中,Lua 语言的标识符是依赖于 locale 的 [1]。在 5.2 中,“Lua 标识符不能使用依赖于 locale 的字符 [2]。”

Lua 代码中的数字必须以 C locale 的风格书写

print(1.23) -- always valid
print(1,23) -- always interpreted as two numbers: "1" and "23".

数字测试

> assert(os.setlocale('fr_FR'))
> = 1,23 , 1.23
1	23	1,23
> =loadstring("return 1,23 , 1.23")()
1	23	1,23
> print(1.23, tostring(1.23), string.format("%0.2f",1.23))
1,23	1,23	1,23
> 
> ="1.23" + 0
stdin:1: attempt to perform arithmetic on a string value
stack traceback:
	stdin:1: in main chunk
	[C]: in ?
> ="1,23" + 0
1,23
> =tonumber("1.23"), tonumber("1,23")
nil	1,23

以上结果将取决于 luaconf.h 的设置,5.2.0rc2 中提到了这一点。

/*
@@ lua_str2number converts a decimal numeric string to a number.
@@ lua_strx2number converts an hexadecimal numeric string to a number.
** In C99, 'strtod' do both conversions. C89, however, has no function
** to convert floating hexadecimal strings to numbers. For these
** systems, you can leave 'lua_strx2number' undefined and Lua will
** provide its own implementation.
*/
#define lua_str2number(s,p)	strtod((s), (p))

#if defined(LUA_USE_STRTODHEX)
#define lua_strx2number(s,p)	strtod((s), (p))
#endif

如果您禁用了 LUA_USE_STRTODHEX,那么将使用 Lua 自有的 lua_strx2number 实现。这依赖于与 locale 无关的函数(例如 lctype.c 中的 lisspace)。请观察这个奇怪的行为。

Lua 5.2.0  Copyright (C) 1994-2011 Lua.org, PUC-Rio
> assert(os.setlocale'fr_FR')
> return tonumber'1.5', tonumber'1,5'
nil	1,5
> return tonumber'0x1.5', tonumber'0x1,5'
1,3125	nil

字符类测试

function findrange(pat)
  for i=0,255 do
    if string.char(i):match(pat) then
      print(i, string.char(i))
    end
  end
end

assert(os.setlocale'C')
findrange'%a' --> A-Z,a-z
assert(os.setlocale'en_US.ISO-8859-1')
findrange'%a' --> A-Z,a-z,\170,\181,\186,\192-\255
findrange'%l' --> a-z,\181,\223-\255

其他类,如 isspace (%w) 和 isdigit (%d),可能比 C locale 返回更多字符 [3]

string.lowerstring.upper 也依赖于 locale。

字符串比较

> assert(os.setlocale'C')
> return "�" < "e"
false
> assert(os.setlocale('fr_FR'))
> return "�" < "e"
true

日期测试

> assert(os.setlocale('C'))
> =os.date()
Sat Nov 26 13:22:56 2011
> assert(os.setlocale('fr_FR'))
> =os.date()
sam. 26 nov. 2011 13:22:56 EST

历史说明

-- This error occurred in 5.0 (but not 5.1 or above)
-- https://lua.ac.cn/pil/22.2.html
print(os.setlocale('pt_BR'))    --> pt_BR (Portuguese-Brazil)
print(3,4)                      --> 3    4
print(3.4)       --> stdin:1: malformed number near `3.4'

另请参阅


RecentChanges · preferences
编辑 · 历史
最后编辑于 2018 年 1 月 3 日 下午 6:55 GMT (差异)