Menu
CoddyTech

Scripts to require

Lesson 29 of 48 in Coddy's Lua for GDScript Developers course.

A GDScript file defines a class; preload can obtain that script resource so callers can use its static methods or create instances. Lua modules conventionally return a table of exported functions. A caller obtains it with require("pricing"), which normally searches for a corresponding module file and caches the result. Requiring a module does not create a fresh model instance each time. The examples below keep everything in one file: GDScript uses an inner helper class, while Lua registers a module loader in package.preload. In the exercises, put the helper in its own file and return its export table.

GDScript 4

extends SceneTree
class Pricing:
    static func subtotal(price, quantity):
        return price * quantity
func _init():
    print(Pricing.subtotal(6, 3))
    quit()

Lua 5.1

package.preload["pricing"] = function()
  local Pricing = {}
  function Pricing.subtotal(price, quantity)
    return price * quantity
  end
  return Pricing
end
local pricing = require("pricing")
print(pricing.subtotal(6, 3))

Porting trap

A Lua module is not automatically a Godot script class or an autoload node. Export a constructor explicitly when callers need separate state.

challenge icon

Challenge

Easy

Input is integer price and nonnegative quantity. Implement subtotal in pricing.lua and call it from app.lua. Return the product. Do not print during require.

Edit app.lua, pricing.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Public API checks: pricing.subtotal(price, quantity) must work independently of app.run, including zero quantity and signed price. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.

Try it yourself

-- Public API checks
do
local pricing=require("pricing")
assert(pricing.subtotal(4,3)==12 and pricing.subtotal(4,0)==0 and pricing.subtotal(-2,3)==-6,"pricing.subtotal must implement the public product API")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for GDScript Developers

Practice on your own: Online Lua compiler