Lua:角色的类型

前端之家收集整理的这篇文章主要介绍了Lua:角色的类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要一个功能

  1. function getCharType(c)
  2. local i = string.byte(c) -- works only for 1 byte chars
  3. if (i > 48) and (i < 57) then return 1 end
  4. if (i > 97) and (i < 122) then return 2 end
  5. return 0
  6. end

应该返回

  1. 2 - if c is a letter
  2. 1 - if c is a digit
  3. 0 - if c is a symbol (anything else)

c本身已经是小写字符:charType = getCharType(string.lower(Character)).如果可以使用Unicode字符,那就没问题了.

上面的getCharType(“ö”)是0.

解决方法

要确定非ASCII字符是大写还是小写字母还是数字,您需要Unicode数据.维基百科上的 Module:Unicode data具有这样的函数,它使用 Module:Unicode data/category( General Category的Unicode字符的数据).

以下是Module:Unicode数据中lookup_category函数的改编.我没有包含Unicode数据(模块:Unicode数据/类别);你必须从上面的链接复制它.

  1. local category_data -- set this variable to the text of Module:Unicode data/category above
  2. local floor = math.floor
  3. local function binary_range_search(code_point,ranges)
  4. local low,mid,high
  5. low,high = 1,#ranges
  6. while low <= high do
  7. mid = floor((low + high) / 2)
  8. local range = ranges[mid]
  9. if code_point < range[1] then
  10. high = mid - 1
  11. elseif code_point <= range[2] then
  12. return range,mid
  13. else
  14. low = mid + 1
  15. end
  16. end
  17. return nil,mid
  18. end
  19.  
  20. function get_category(code_point)
  21. if category_data.singles[code_point] then
  22. return category_data.singles[code_point]
  23. else
  24. local range = binary_range_search(code_point,category_data.ranges)
  25. return range and range[3] or "Cn"
  26. end
  27. end

函数get_category采用代码点(数字)并返回常规类别的名称.我猜你感兴趣的类别是Nd(数字,十进制数字)和以L(字母)开头的类别.

您将需要一个将字符转换为代码点的函数.如果文件以UTF-8编码并且您使用的是Lua 5.3,则可以使用utf8.codepoint函数:get_category(utf8.codepoint(‘ö’))将导致’Ll’.您可以将类别代码转换为上述函数使用的数字值:函数category_to_number(类别)如果category ==“Nd”则返回1 elseif类别:sub(1,1)==“L”然后返回2否则返回0结束.

猜你在找的Lua相关文章