总结几个LUA实用的函数

12320阅读 2评论2014-08-02 forgaoqiang
分类:嵌入式

    
    lua语言作为苹果iOS系统支持的一种编程语言,同时常见于游戏脚本(比如冰封王座等),也常用与嵌入式系统(OpenWRT堪称经典),但是Lua语言自身却缺少一些实用的,或者说是常用的函数,这里根据经验编写和总结了一些实用函数供大家使用。


  1. -- 读文件的函数,把整个文件内容读取并返回的函数
  2. function readFiles(fileName)
  3.     local f = assert(io.open(fileName,'r'))
  4.     local content = f:read("*all")
  5.     f:close()
  6.     return content
  7. end

  1. --分割字符串的函数,类似PHP中的explode函数,使用特定的分隔符分割后返回”数组(lua中的 table)“
  2. function Split(szFullString, szSeparator)
  3.  local nFindStartIndex = 1
  4.  local nSplitIndex = 1
  5.  local nSplitArray = {}
  6. while true do
  7.    local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)
  8.    if not nFindLastIndex then
  9.     nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))
  10.     break
  11.    end
  12.    nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)
  13.    nFindStartIndex = nFindLastIndex + string.len(szSeparator)
  14.    nSplitIndex = nSplitIndex + 1
  15. end
  16.  return nSplitArray
  17. end

  1. -- 这个也算是一个实用函数吧,头部定义一个变量控制整个Debug的输出
  2. function Debug(DebugMes)
  3. if debug == "on" then
  4. print(DebugMes)
  5. end
  6. end

  1. -- 类似PHP中的Trim函数,用来去掉字符串两端多余的空白符(white Space)
  2. function trim(s)
  3.  return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
  4. end
lua中甚至都没有延时函数,真是要命呢~
  1. -- 延时函数,有点猥琐的实现,利用系统的ping的延时
  2. function sleep(n)
  3.    if n > 0 then os.execute("ping -n " .. tonumber(n + 1) .. " localhost > NUL") end
  4. end

上一篇:《WebKit技术内幕》 试读感想
下一篇:Ubuntu 12.04 Freeradius 安装实际过程

文章评论