Lua覚書

代入

普通

 x = 123   -- no diff between int and float
 s = "ho\tge" -- "ho   ge"
 t = [[ho\tge]]  -- "ho\tge"

(FEP died!!)I'm not sure there's any differences between single/double quoted string.

ローカル グローバル

普通に書くと何でもグローバル。local つけるとローカル
_Gでグローバルテーブルを参照。localにhideされたときなんかに。

> glbl = 10
> do 
>>  local glbl = 200
>>  print (_G.glbl)
>> end
10

テーブル:

ハッシュ? と思ったんだけど、シンボルしか受け付けてくれなさそう

 msg_NG = { 404 = [[Not Found]], 500 = [[Internal Server Error]] } ×
 msg_FX = { [404] = [[Not Found]], [500] = [[Internal Server Error]] } ○
 msg_OK = { NotFound = 404, ServerError = 500 }

あくまでstructとして。 []でくくればいいのか。なんか違和感。

文字連結

.. でOK

配列

tableのキーが数字だと

> b = {[1]=3, [2]=2, [3]=1}

配列になる

>  t = {'ばか', 'とは', 'なんだ', 'ばか', 'とは'}
> print(t[1]..t[2]..t[4]..t[3])
ばかとはばかなんだ
> print(#t)
5

1始まりがちょっと違和感。

traverse

テーブル要素を舐めるにはpairs()を使う。

> for key,val in pairs(msg_FX) do
   print (key, val)
  end
404	Not Found
500	Internal Server Error

pairs()の中は

function: 0x62a0b0	table: 0x64d800	nil

良く分からない。多分コルーチンだろう。

関数定義

Rっぽ

 f = function() print("test") end

再起もそのまま

 fact = function(x) if x == 0 or x == 1 then return 1 else return x*fact(x-1) end end
>> print(f(10))
3628800
> 

コルーチン

Threadかと思いきや、Fiberだった. 状態つき関数というか、yield的な使い方がメインかな。

> counter = function() local c = 1 while 1 do coroutine.yield(c) c=c+1 end end
> c1 = coroutine.wrap(counter)
> c2 = coroutine.wrap(counter)
> c1()
> c1()
> c1()
> c2()
> print (c1(), c2())
4	2
> print (c1(), c2())
5	3
> print (c1(), c2())
6	4
> print (c1(), c2())
7	5
> print (c1(), c2())
8	6

yieldつきの関数を実行するなんて蛮行をすると、、、普通に怒られる

> counter()
attempt to yield across metamethod/C-call boundary
stack traceback:
	[C]: in function 'yield'
	stdin:1: in function 'counter'
	stdin:1: in main chunk
	[C]: ?