Lua 技巧

2015-10-29  本文已影响124人  曾令伟

1、剔除字符串中的“,”逗号

function LuaKill:findNum( str )

       local allStr = str .. ","

      local tabNum = {}

      while allStr do

              local len = string.len( allStr )

              local m = string.find( allStr, "," )

              local num = string.sub(allStr, 1, m-1)

              table.insert( tabNum, 1, num )

             if m >= len then

                       allStr = nil

                       return    tabNum

             end 

            allStr = string.sub( allStr, m+1, len )

      end

     return tabNum

end

这个函数可以从字符串中剔除逗号拿到数据

比如:  str = "1,2,3,4,5,6,7,8,9,10"

调用    findNum( str )

返回一个装有  1到 10 数字的表{1,2,3,4,5,6,7,8,9,10}

2、从字符串中取数字

function LuaKill:findNum(  str  )

         local num = ""

         local len = string.len( str )

         for i = 1, len do

                local assic = string.byte( str, i )

                if assic <= 57 and assic>= 48 then

                            num = num .. string.sub( str, i, i )

                end

        end

       return tonumber( num)

end

例如:  str = “asdf123shjk”

find(str)  结果为: 123

3、Lua使用Switch

Lua中没有Switch关键字   但是我们在程序中很多时候都要用到,Lua也可以实现Switch,如下:

function LuaKill:switch( tag )

        local onButtonClicked = {

                    [1] = function()

                             print("tag = 1")

                   end,

                   [2] = function()

                             print("tag = 2")

                   end,

                  [3] = function()

                             print("tag = 3")

                   end,

        }

       onButtonClicked [tag]( )

end

根据Tag的不同调用 不同的函数

上一篇下一篇

猜你喜欢

热点阅读