Lua 本地化

lua-users home
wiki

这里有一些关于 Lua 中 [本地化] 的笔记。

Lua 受到标准 C 的很大影响,因此 C 对本地化的处理方式在很大程度上会影响 Lua。

可以使用 [os.setlocale] 函数获取或设置当前本地化。

警告:os.setlocale 在内部调用 C [setlocale] 函数,该函数会全局设置当前进程中所有 Lua 状态和所有操作系统线程的本地化。但是,一些 C 实现提供了非标准函数(例如 Microsoft 的 [_configthreadlocale]),以便只影响当前的操作系统线程。

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

Lua 语法

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

Lua 代码中的数字必须使用 C 本地化风格编写

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 实现。这依赖于与本地化无关的函数(例如 lisspace 来自 lctype.c)。观察奇怪的行为

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 本地化更多的内容 [3]

string.lowerstring.upper 也依赖于本地化。

字符串比较

> 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://www.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'

另请参阅


最近更改 · 首选项
编辑 · 历史记录
上次编辑于 2018 年 1 月 4 日凌晨 12:55 GMT (差异)