- The Programming Language Lua Lua 本家。
- プログラミング言語Luaの紹介
- Lua 5.1 リファレンスマニュアル Lua 5.1 Reference Manual の日本語訳。
- Luaを使ってみよう
- Luaプログラミング入門
- Lua基礎文法最速マスター @ 良いもの。悪いもの。
- LuaTeX Lua によるスクリプティングが可能な TeX。バージョン 1.0 が 2012年にリリース予定、とのこと。TeXShop 2.34 のリリースノートによると、最新版の TeXShop では LuaTeX が(実用に堪えうるまでに開発が進んだとの判断から)デフォルトのタイプセットエンジンになった模様。この辺りが Lua に興味を持ち始めたきっかけ。
たとえば MacでLuaを使う@Jewel-mmo開発日記 が参考になる。
(私は上記リンク先の方法に従った。
MacPortsを利用するのが簡単のようだけれど、
私の環境では何やら依存関係でのエラーが出てうまくいかなかった)
function gcd(a, b) while b > 0 do a, b = b, a % b end return a end a = 96481747 b = 66602309 print( "GCD of " .. a .. " and " .. b .. " is " .. gcd(a, b) .. "." )
Lua では多重代入が出来るので、互除法のアルゴリズムがあっさりと表現出来る。
Accuracy = 1/10^10 function AGM(a,b) while (math.abs(a-b) > Accuracy) do a, b = (a+b)/2, math.sqrt(a*b) end return a end print( AGM(1, math.sqrt(2)) )これも多重代入の応用.
comp = {} m = 1000000 _m = math.ceil(math.sqrt(m)) start_time = os.date() for d = 2, _m do if not comp[d] then i=math.ceil(math.sqrt(d)) while i * d <= m do comp[i * d] = 1 i = i + 1; end end end n = 0 for i = 2, m do if not comp[i] then n = n + 1 io.write(string.format("%7d ",i)) if n % 10 == 0 then print "" end end end print ("\nThere are " .. n .. " primes less than " .. m .. ".") end_time = os.date() print ("begin: " .. start_time .. "\n end: " .. end_time)m 以下の素数を全て求めて、その個数も返す。
ついでに計算の開始時刻と終了時刻を表示する。
function enter () local t t = {} io.write ( "a b -> " ) string.gsub (io.read (), "(%S+)", function (v) table.insert (t, tonumber (v)) end) return t[1], t[2] end function solutions (a, b) local n, x, y, q n = 1 x = 1 y = 0 q = {} while b > 0 do a, b, n, q[n] = b, a % b, n + 1, math.floor (a / b) end for i = n - 1, 1, -1 do x, y = y, x - q[i] * y end return x, y, a end a, b = enter () x, y, d = solutions (a, b) print ( a .. " x + " .. b .. " y = " .. d .. " ==> x = " .. x .. ", y = " .. y )
実行すると数値の入力を求められる。
空白で区切って2つの正整数 a, b を入力すると
不定方程式 a x + b y = gcd(a, b) の一つの整数解を求めて返す。
入力の処理部分は Luaを使ってみよう を参照した。
Accuracy = 1/10^10 function mylog(a) local e,l,n,r,R -- e=error, l=log value e = a-1 l = 0 n = 0 r = (a-1)/(a+1) R = r^2 while (e > Accuracy) do e, l, r, n = (2*n+1)/(2*n+3)*R*e, l+2/(2*n+1)*r, r*R, n+1 end return l end for k=1, 99 do io.write( string.format( "ln(%2d) = %.10f", k, mylog(k) ) ) io.write( " " ) io.write( string.format( "log(%2d) = %.10f\n", k, mylog(k)/mylog(10) ) ) end
自然対数と常用対数の値を,log(1+x) のマクローリン展開から導かれる級数表示を利用して計算する.
コメントをかく