프로그래밍 언어/Lua

Lua 5. 모듈(Module)

yozura 2024. 8. 10. 22:55
반응형

모듈(Module)

모듈의 정의

-- hello_module.lua
local hello_module = {}

function hello_module.greet(name)
    return "Hello, " .. name
end

return hello_module

모듈의 사용

-- main.lua
local hello_module = require("hello_module")
print(module.greet("Lua")) -- Hello, Lua
  • hello_module.lua 파일에서 hello_module 테이블은 모듈 내 함수를 포함한다.
  • 모듈 테이블을 파일에서 return 하면 다른 Lua 파일에서 해당 모듈을 사용할 수 있다.
  • 다른 Lua 파일에서 모듈을 require("module path") 함수를 사용할 수 있다.

모듈 사용 예시

모듈로 하여금 메타 테이블을 객체지향적으로 사용할 수 있다.

모듈의 정의

-- computer.lua
local Computer = {}
Computer.__index = Computer

function Computer:new(CPU, RAM, GPU)
    local self = setmetatable({}, Computer)
    self.CPU = CPU
    self.RAM = RAM
    self.GPU = GPU
    return self
end

function Computer:description()
    print("CPU : " .. self.CPU)
    print("RAM : " .. self.RAM)
    print("GPU : " .. self.GPU)
end

return Computer

모듈의 사용

-- main.lua
local Computer = require("computer")
local myComputer = Computer:new("5600X", "16GB", "RTX4090")
myComputer:description()
--[[
    Output:
    CPU : 5600X
    RAM : 16GB
    GPU : RTX4090
]]