Lua 的一些技巧
Lua 的一些技巧
连续赋值
C#
1
y = x = calc()
Lua
1
2
3
local csl_0 = calc()
y = csl_0
x = csl_0
Lua
如何用Lua实现高效的 Swith 语法
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
switch (s)
{
case ManagedStrippingLevel.Disabled:
break;
case ManagedStrippingLevel.Low:
break;
case ManagedStrippingLevel.Medium:
break;
case ManagedStrippingLevel.High:
break;
default:
break;
}
Lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
repeat
-- case ManagedStrippingLevel.Disabled
if v == ManagedStrippingLevel.Disabled then
break
end
-- case ManagedStrippingLevel.Low:
if v == ManagedStrippingLevel.Low then
break
end
-- case ManagedStrippingLevel.Medium:
if v == ManagedStrippingLevel.Medium then
break
end
-- case ManagedStrippingLevel.High:
if v == ManagedStrippingLevel.High then
break
end
-- default:
print("default")
until(true)
如何使用Lua实现Continue
C#
1
2
3
4
5
6
7
8
9
10
11
while (true)
{
if (need_continue)
{
continue;
}
if (need_break)
{
break;
}
}
Lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
while(true)
do
local flag
repeat
if need_continue then
flag = flag_continue
end
if need_break then
flag = flag_break
break
end
until(true)
if flag == flag_break then
break
end
end
如何实现不定参数
C#
(不定参数会被翻译成数组传值)
1
2
3
4
5
6
7
8
9
private void test()
{
args("a","b","C");
}
private void args(params string[] varArgs)
{
}
Lua
1
条件语句
Lua
使用一个wrap函数包装x表达式,当x为nil或者false时返回特定的标记,最后在unwrap时还原
1
2
var = cond ? x : y
local var = unwrap(cond and wrap(x) or y)
本文由作者按照 CC BY 4.0 进行授权