🌙 Lua J2ME ‐ Documentation
Lima edited this page 2025-10-20 08:45:02 -03:00

🌍 Overview

This is a complete implementation of the Lua language for the J2ME (Java Micro Edition) platform, designed to work on mobile devices with limited resources. The implementation includes a parser, interpreter, and various standard libraries adapted for the J2ME environment.

Key Features

  • Complete Language: Supports most Lua language concepts
  • J2ME Optimized: Adapted for memory-limited mobile devices
  • Native Libraries: Includes adapted versions of standard Lua libraries
  • Graphical Interface: Integration with J2ME UI (Display, Form, List, etc.)
  • Networking: HTTP, TCP/IP socket support
  • File System: File system access via RMS

📊 Comparison Table: Original Lua vs Lua J2ME

Feature Original Lua 🐧 Lua J2ME 📱
Platform Cross-platform J2ME only
Memory No restrictions Limited (mobile devices)
Libraries Complete Adapted/Reduced
UI Terminal/Console J2ME Display (Form, List, Alert)
Networking Full socket support Basic HTTP, Socket
File System Complete RMS (Record Management System)
Threading Full support Limited by J2ME
Garbage Collection Advanced Basic (System.gc())

🛠️ Native Functions Implemented

🌍 Global Functions

Function Description
print(...) Output text to console
error(msg) Throws error with message
pcall(f, ...) Protected function call
require(mod) Loads Lua modules
load(string) Loads Lua code
pairs(t) Iterates over tables
ipairs(t) Advanced iterates over tables
collectgarbage(opt) Controls garbage collection
tostring(v) Converts to string
tonumber(v) Converts to number
select(index, ...) Selects arguments
type(v) Returns value type
getAppProperty(key) Gets application properties

💻 OS Library

Function Description
os.execute(cmd) Executes system commands
os.getenv(var) Gets environment variables
os.clock() Program execution time
os.setlocale(loc) Sets locale
os.exit(code) Terminates execution
os.date() Current date/time
os.getpid() Process ID
os.setproc(attr, val) Sets process properties
os.getproc(pid, field) Gets process information
os.getcwd() Current directory

📁 IO Library

Function Description
io.read([source]) Reads from file/stream
io.write(data, [target]) Writes to file/stream
io.close(stream) Closes stream
io.open(file) Opens file

🔤 String Library

Function Description
string.upper(s) Converts to uppercase
string.lower(s) Converts to lowercase
string.len(s) String length
string.find(s, pattern) Finds pattern in string
string.match(s, pattern) Matches pattern in string
string.reverse(s) Reverses string
string.sub(s, i, j) Substring
string.hash(s) Hash code
string.byte(s, i, j) Converts to bytes
string.char(...) Converts bytes to string
string.trim(s) Trims extra spaces

🗂️ Table Library

Function Description
table.insert(t, [pos], value) Inserts element into table
table.concat(t, [sep], [i], [j]) Concatenates elements
table.remove(t, [pos]) Removes element
table.sort(t) Sorts table
table.move(t, f, t, len) Moves elements
table.unpack(t, [i], [j]) Unpacks table
table.pack(...) Packs arguments
table.decode(str) Decodes string to table

🎨 Graphics Library

Function Description
graphics.Alert(config) Alert dialog
graphics.BuildScreen(config) Creates form
graphics.BuildList(config) Creates list
graphics.BuildQuest(config) Creates input field
graphics.BuildEdit(config) Creates text box
graphics.SetTitle(screen, title) Sets title of screen
graphics.SetTicker(text) Sets current screen ticker
graphics.WindowTitle(title) Sets title of Main Screen
graphics.display(screen) Displays screen
graphics.append(screen, item) Adds item into screen
graphics.render(file) Renders image from file

🌐 Socket Library

Function Description
socket.connect(url) TCP connection
socket.peer(conn) Peer address
socket.device(conn) Local address
socket.server(port) Socket server
socket.accept(server) Accepts connection
socket.http.get(url, headers) HTTP GET request
socket.http.post(url, data, headers) HTTP POST request

Java Library

Function Description
java.class(name) Checks if class exists
java.getName() Application name
java.delete(table, field) Delete a field from table in Java
java.midlet.sessions Table with logged sessions, for command who
java.midlet.cache Cached files in MIDlet
java.midlet.build MIDlet Build Code

📝 Usage Example

-- Hello World
print("Hello Lua J2ME World!")

-- Table manipulation
local t = { 1, 2, 3, name = "Lua" }
table.insert(t, 4)
print(table.concat(t, ", "))

-- Graphical interface
local screen = graphics.BuildScreen({
    title = "My App",
    fields = {
        { type = "text", value = "Welcome!" },
        { type = "field", label = "Name:", value = "" }
    }
})
graphics.display(screen)

🎨 Basic Graphics Example

-- Simple alert
graphics.Alert({
    title = "Welcome",
    message = "Hello Lua J2ME!",
    button = {label = "OK", root = function() print("Closed!") end}
})

-- Form with multiple components
local screen = graphics.BuildScreen({
    title = "My Application",
    fields = {
        {type = "text", value = "Welcome to my app!", layout = "default"},
        {type = "image", img = "/images/logo.png"},
        {type = "field", label = "Username:", value = "", length = 20},
        {type = "choice", label = "Options:", mode = "exclusive", 
         options = {"Option 1", "Option 2", "Option 3"}},
        {type = "gauge", label = "Progress:", interactive = false, max = 100, value = 50}
    },
    button = {label = "Submit", root = function(data) 
        print("Form submitted: " .. data[1]) 
    end}
})
graphics.display(screen)

📋 List Example

local list = graphics.BuildList({
    title = "Main Menu",
    type = "implicit",
    icon = "/images/icon.png",
    fields = {
        "Settings",
        "Games", 
        "Tools",
        "Exit"
    },
    button = {label = "Select", root = function(selected)
        print("Selected: " .. selected[1])
    end}
})
graphics.display(list)

Input Dialog Example

local quest = graphics.BuildQuest({
    title = "Login",
    label = "Enter password:",
    type = "password",
    key = "user_password",
    button = {label = "Login", root = function(password)
        if password == "secret" then
            print("Access granted!")
        else
            print("Wrong password!")
        end
    end}
})
graphics.display(quest)

⚠️ Limitations

  • Performance: Slower than native Lua due to JVM
  • Memory: Severe memory constraints
  • Libraries: Reduced functionality compared to full Lua
  • Platform: Limited to J2ME ecosystem

🎯 Conclusion

Lua J2ME is an impressive implementation that brings the power of Lua language to older mobile devices with J2ME. Although it has limitations compared to the original implementation, it offers a robust solution for scripting in resource-limited environments.