---
title: "switch"
author: "arust"
date: "2009-05-11T11:16:27Z"
tags: []
categories: ["编程语言"]
slug: "switch"
draft: false
lastmod: "2009-12-15T13:31:34Z"
id: 383486
url: "https://haiyi.iteye.com/blog/383486"
---

一直对 Lua 没有 switch 语句耿耿于怀，每次检查代码时都不得不在令人眼花潦乱的 if then elseif 语句中检查配对关系，身心俱疲，视力受损。 :? 

直到今天早晨突然想到可以用 repeat until 语句模拟，试验了一下，效果还不错，代码结构顿时清晰了许多。

而且，Lua 中的变量没有预定义的类型这一特性，使得这种写法比起 C 语言的 switch 语句更加灵活和强大。



```Lua

table ={item="item"}

function func()
    print("hello world!")
end

function l_switch(str)
    repeat
        if str == true then
            print(str)
            break
        end
        if str == "abc" then
            print(str)
            break
        end
        if str == 123 then
            print(str)
            break
        end
        if str == func then
            func()
            break
        end
        if str == table then
            print(str.item)
            break
        end
        --default:
        print(str)
    until true
end

l_switch(true)
l_switch("abc")
l_switch(123)
l_switch(func)
l_switch(table)
l_switch(abc)

```


代码输出结果：


> true
> abc
> 123
> hello world!
> item
> nil
>