Lua のモジュール

no extension

NYAGOS 4.1.0_0 がリリースされた。 主な変更点は ln コマンドが追加されたことのようだ。

ただ,私の場合はより切実な問題があって, -f オプションで Lua のスクリプトを実行させた場合に module() 関数が使えなくなった。 Lua は不案内なので知らなかったのだが module() 関数は Lua 5.2 で deprecated になっていたらしい。 逆になんで今まで使えてたのかは分からない。

module() 関数が使えないので require() で外部ファイルを呼び出すとファイル内の記述がそのまま実行される。

以前なら module1.lua に

module("module1", package.seeall)

function method1()
    return "Method 1"
end

function method2()
    return "Method 2"
end

と定義しておけば

require("module1")

nyagos.write(module1.method1().."\n")
nyagos.write(module1.method2().."\n")

と記述できた。 もし同じように機能させたいなら module1.lua を

module1 = {}

module1.method1 = function()
    return "Method 1"
end

module1.method2 = function()
    return "Method 2"
end

と記述するのが一番簡単なようだ。 module1 を関数テーブルとして定義するわけだ。

あるいは module1.lua を

local module1 = {}

module1.method1 = function()
    return "Method 1"
end

module1.method2 = function()
    return "Method 2"
end

return module1

としておいて,呼び出し側を

local module1 = require("module1")

nyagos.write(module1.method1().."\n")
nyagos.write(module1.method2().."\n")

とすればグローバル領域を汚さずに済むだろう。