Show List

Lua standard library

The Lua standard library is a collection of modules and functions that are included with the Lua programming language. These modules provide a wide range of functionality that can be used to perform common programming tasks, such as working with strings, files, and network connections.

Here's an overview of some of the key modules in the Lua standard library, along with some code examples:

  • string: This module provides functions for working with strings, such as string.sub, string.find, and string.gsub. Here's an example of using the string.sub function to extract a substring from a string:

lua
Copy code
local str = "hello world" print(string.sub(str, 1, 5)) -- prints "hello"
  • table: This module provides functions for working with tables, such as table.insert, table.remove, and table.sort. Here's an example of using the table.sort function to sort a table of numbers:

  • lua
    Copy code
    local nums = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5} table.sort(nums) print(table.concat(nums, ", ")) -- prints "1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9"
  • io: This module provides functions for working with files and input/output streams, such as io.open, io.write, and io.read. Here's an example of using the io.open function to open a file and read its contents:

  • lua
    Copy code
    local file = io.open("myfile.txt", "r") local content = file:read("*all") file:close() print(content)
  • os: This module provides functions for working with the operating system, such as os.time, os.date, and os.execute. Here's an example of using the os.date function to get the current date and time:

  • lua
    Copy code
    local t = os.date("*t") print(t.year, t.month, t.day, t.hour, t.min, t.sec)
  • math: This module provides functions for working with mathematical operations, such as math.random, math.floor, and math.sin. Here's an example of using the math.random function to generate a random number:

  • lua
    Copy code
    math.randomseed(os.time()) local num = math.random(1, 100) print(num)
  • socket: This module provides functions for working with network connections, such as socket.connect, socket.bind, and socket.send. Here's an example of using the socket.connect function to connect to a remote server:

  • lua
    Copy code
    local socket = require("socket") local conn = socket.connect("www.example.com", 80) conn:send("GET / HTTP/1.0\r\n\r\n") local response = conn:receive("*all") conn:close() print(response)

    These are just a few examples of the modules and functions available in the Lua standard library. The full documentation for the standard library can be found in the Lua reference manual.


        Leave a Comment


    • captcha text