Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

TOML v1.0.0 parser and serializer for Lua. Powered by toml++.

License

NotificationsYou must be signed in to change notification settings

LebJe/toml.lua

Repository files navigation

TOML v1.0.0 parser and serializer for Lua. Powered bytoml++.

Build and Test on MacOSBuild and Test on LinuxBuild and Test on WindowsLuaRocks

toml.lua is aLua wrapper aroundtoml++, allowing you to parse and serializeTOML in Lua.

Table of Contents

Created bygh-md-toc

Installation

Requirements

  • A C++ 17 compiler (Clang, GCC, MinGW)
  • CMake
  • Lua C headers (lua.h,lualib.h, andlauxlib.h)
  • Lua library (e.g.liblua51.<so|dylib|dll>)
  • Lua >= 5.1 or LuaJIT

LuaRocks

MacOS and Linux

luarocks install toml

Windows

LLVM

If you have installed Clang (https://llvm.org), and CMake is configured to use it, you can run:

luarocks install toml
MinGW

If you have installedMinGW, and CMake is configured to use it, you can run:

luarocks config variables.LINK_FLAGS"path\to\LuaJIT\bin\lua51.dll"luarocks install tomlluarocks config variables.LINK_FLAGS--unset

Manual Compilation

MacOS and Linux

  1. Runcmake -S . -B build -G <generator-name> to generate the required files.

If you have a non standard Lua install location, add the environment variableLUA_DIR and have it point to the directory containing theinclude andlib folders for your Lua installation. For example:LUA_DIR=/usr/local/openresty/luajit cmake -S . -B build -G <generator-name>

  1. Runcmake --build build --config Release to build the project.
  2. You will find thetoml.so dynamic library in thebuild folder.

Tip: usecmake --help to see a list of available generator names.

The above is based off ofxpol/lua-rapidjson's README.

Windows

If LuaJIT is not installed, or your installation does not have the Lua headers, go toinstall LuaJIT.

Build with MinGW

InstallMinGW (choco install mingw), then:

cmake.exe-S.-B build-G"MinGW Makefiles"-DLUA_INCLUDE_DIR="path\to\LuaJIT\include"-DLINK_FLAGS="path\to\LuaJIT\bin\lua51.dll"cmake.exe--build build--config Release

You'll find thetoml.dll file in thebuild directory.

Build with LLVM

InstallLLVM andNinja (choco install llvm ninja), then:

cmake.exe-S.-B build-G"Ninja Multi-Config"-DLUA_INCLUDE_DIR="path\to\LuaJIT\include"cmake.exe--build build--config Release

You'll find thetoml.dll file in thebuild directory.

Install LuaJIT

If you don't have LuaJIT, or your installation does not have the Lua headers, you can:

  1. InstallMinGW (choco install mingw)

  2. Runscripts\buildLuaJIT.ps1:

powershell scripts\buildLuaJIT.ps1-installDir"LuaJIT"

to build and install LuaJIT.

Usage

Decoding

localtomlStr=[[a = 1275892b = 'Hello, World!'c = trued = 124.2548[e]f = [ 1, 2, 3, '4', 5.142 ]g = 1979-05-27h = 07:32:00i = 1979-05-27T07:32:00-07:00]]localtoml=require("toml")localinspect=require("inspect")-- Decode from stringlocalsucceeded,table=pcall(toml.decode,tomlStr)-- Decode from filesucceeded,table=pcall(toml.decodeFromFile,"configuration.toml")ifsucceededthen-- Use `table`.print(inspect(table))else-- Error details are in `table`.end--[[{a = 1275892,b = "Hello, World!",c = true,d = 124.2548,e = {f = { 1, 2, 3, "4", 5.142 },g = <userdata 1> -- 1979-05-27,h = <userdata 2> -- 07:32:00,i = <userdata 3> -- 1979-05-27T07:32:00-07:00}}--]]

Decoding Options

temporalTypesAsUserData
  • temporalTypesAsUserData = true: The userdata typestoml.Date,toml.Time, andtoml.DateTime are used to represent TOML date and time types.

  • temporalTypesAsUserData = false: Lua tables are used to represent TOML date and time types.

The default value istrue

formattedIntsAsUserData
  • formattedIntsAsUserData = true: The userdata typetoml.Int is used to represent integers in octal, binary, or hexadecimal format.
  • formattedIntsAsUserData = false: Integers in octal, binary, or hexadecimal format will be represented in decimal.

The default value isfalse

localtomlStr=[[date = 1979-05-27time = 07:32:00datetime = 1979-05-27T07:32:00-07:00hexadecimal = 0x16C3binary = 0b110110011011octal = 0x169F]]localtable1=toml.decode(tomlStr, {temporalTypesAsUserData=true,formattedIntsAsUserData=true })localtable2=toml.decode(tomlStr, {temporalTypesAsUserData=false,formattedIntsAsUserData=false })print(inspect(table1))--[[{date = <userdata 1> -- 1979-05-27, <-- toml.Datetime = <userdata 2> -- 07:32:00 <-- toml.Timedatetime = <userdata 3> -- 1979-05-27T07:32:00-07:00, <-- toml.DateTimebinary = <userdata 4> -- 0b10011011, <-- toml.Int (with `toml.formatting.int.binary` flag)hexadecimal = <userdata 5> -- 0x16c3, <-- toml.Int (with `toml.formatting.int.octal` flag)octal = <userdata 6> -- 0x169f, <-- toml.Int (with `toml.formatting.int.hexadecimal` flag)}--]]print(inspect(table2))--[[{date = {day = 27,month = 5,year = 1979},time = {hour = 7,minute = 32,nanoSecond = 0,second = 0},datetime = {date = {day = 27,month = 5,year = 1979},time = {hour = 7,minute = 32,nanoSecond = 0,second = 0},timeOffset = {minutes = -420}},binary = 3483,hexadecimal = 5827,octal = 5791,}--]]

Encoding

localtoml=require("toml")-- Inline tables: https://toml.io/en/v1.0.0#inline-tablelocalinlineTable= {a=1275892,b="Hello, World!",c=true,d=124.2548,}-- Make the table inline.setmetatable(inlineTable, {inline=true })localtable= {e= {f= {1,2,3,"4",5.142 },g=toml.Date.new(1979,05,27),--                year   month   dayh=toml.Time.new(7,32,0,0),--                hour   minute  second   nanoSecondi=toml.DateTime.new(toml.Date.new(1979,05,27),toml.Time.new(7,32,0,0),toml.TimeOffset.new(-7,0)--                   hour   minute)},inlineTable=inlineTable}-- Encode to stringlocalsucceeded,documentOrErrorMessage=pcall(toml.encode,table)-- Encode to file, this will **append** to the file.succeeded,documentOrErrorMessage=pcall(toml.encodeToFile,table,"configuration.toml")-- Encode to file, this will **overwrite** the file.succeeded,documentOrErrorMessage=pcall(toml.encodeToFile,table, {file="configuration.toml",overwrite=true })ifsucceededthen-- Successfully encoded to string / wrote to fileprint(tomlDocumentOrErrorMessage)else-- Error occurredprint(tomlDocumentOrErrorMessage)end--[[inlineTable = { a = 1275892, b = "Hello, World!", c = true, d = 124.2548 }[e]f = [ 1, 2, 3, "4", 5.1420000000000003 ]g = 1979-05-27h = 07:32:00i = 1979-05-27T07:32:00-07:00--]]

Error Handling

localtomlStr=[[a = 1275892b = 'Hello, World!'c = trued = 124. # <-- ERROR: "Expected decimal digit"[e]f = [ 1, 2, 3, '4', 5.142 ]g = 1979-05-27h = 07:32:00i = 1979-05-27T07:32:00-07:00]]localtoml=require("toml")localinspect=require("inspect")localsucceeded,table=pcall(toml.decode,tomlStr)ifsucceededthen-- Use decoded table.print(inspect(table))else-- Error details are in `table`.print(inspect(table))--[[{begin = {column = 9,line = 4},end = {column = 9,line = 4},reason = "Error while parsing floating-point: expected decimal digit, saw '\\n'"}--]]end

Inline Tables

Usesetmetatable(myTable, { inline = true }) to create aninline table.

TOML Conversion

localtoml=require("toml")localtomlStr=[[a = 1275892b = 'Hello, World!'c = trued = 124.2548[e]f = [ 1, 2, 3, '4', 5.142 ]g = 1979-05-27h = 07:32:00i = 1979-05-27T07:32:00-07:00]]

JSON

-- Convert from a stringlocaljson=toml.toJSON(tomlStr)-- or from a tablejson=toml.toJSON(toml.decode(tomlStr))print(json)

YAML

localyaml=toml.toYAML(tomlStr)yaml=toml.toYAML(toml.decode(tomlStr))print(yaml)

Output Formatting

Formatting Integers

localtoml=require("toml")localnormalIntegers= {int1=2582int2=3483int3=5971}print(toml.encode(normalIntegers))--[[int1 = 2582int2 = 3483int3 = 5791--]]localformattedIntegers= {int1=toml.Int.new(2582,toml.formatting.int.octal),int2=toml.Int.new(3483,toml.formatting.int.binary),int3=toml.Int.new(5791,toml.formatting.int.hexadecimal)}print(toml.encode(formattedIntegers))--[[int1 = 0o5026int2 = 0b110110011011int3 = 0x169F--]]-- Use `int` and `flags` properties to assign and retrieve flags and integers.localint=formattedIntegers.int1.intlocalflags=formattedIntegers.int1.flagsformattedIntegers.int1.int=5827formattedIntegers.int1.flags=toml.formatting.int.hexadecimalprint(toml.encode(formattedIntegers))--[[int1 = 0x16C3int2 = 0b110110011011int3 = 0x169F--]]

Formatting TOML, JSON, or YAML

toml.encode,toml.encodeToFile,toml.toJSON, andtoml.toYAML all take an optional second (third in the case oftoml.encodeToFile) parameter: a table containing keys that disable or enable different formatting options.Passing an empty table removes all options, while not providing a table will use the default options.

{--- Dates and times will be emitted as quoted strings.quoteDatesAndTimes=false,--- Infinities and NaNs will be emitted as quoted strings.quoteInfinitesAndNaNs=false,--- Strings will be emitted as single-quoted literal strings where possible.allowLiteralStrings=false,--- Strings containing newlines will be emitted as triple-quoted 'multi-line' strings where possible.allowMultiLineStrings=false,--- Allow real tab characters in string literals (as opposed to the escaped form `\t`).allowRealTabsInStrings=false,--- Allow non-ASCII characters in strings (as opposed to their escaped form, e.g. `\u00DA`).allow_unicode_strings=true,--- Allow integers with `toml.formatting.int.binary` to be emitted as binary.allowBinaryIntegers=true,--- Allow integers with `toml.formatting.int.octal` to be emitted as octal.allowOctalIntegers=true,--- Allow integers with `toml.formatting.int.hexadecimal` to be emitted as hexadecimal.allowHexadecimalIntegers=true,--- Apply indentation to tables nested within other tables/arrays.indentSubTables=false,--- Apply indentation to array elements when the array is forced to wrap over multiple lines.indentArrayElements=false,--- Combination of `indentSubTables` and `indentArrayElements`.indentation=true,--- Emit floating-point values with relaxed (human-friendly) precision.------ Warning: Setting this flag may cause serialized documents to no longer round---- trip correctly since floats might have a less precise value upon being written out--- than they did when being read in. Use this flag at your own risk.relaxedFloatPrecision=false,--- Avoids the use of whitespace around key-value pairs.terseKeyValuePairs=false}

Date and Time

(Creating Date, Time, and DateTime is shown inthe encoding section)

recordDateyear:numbermonth:numberday:numbernew:function(year:number,month:number,day:number):DateendrecordTimehour:numberminute:numbersecond:numbernanoSecond:numbernew:function (hour:number,minute:number,second:number,nanoSecond:number):TimeendrecordTimeOffsetminutes:numbernew:function (hours:number,minutes:number):TimeOffsetendrecordDateTimedate:Datetime:TimeTimeOffset:nil |TimeOffsetnew:function(date:Date,time:Time):DateTimenew:function(date:Date,time:Time,timeOffset:TimeOffset):DateTimeend

The comments for the options are fromthe tomlplusplus documentation

Dependencies

Licenses

Thetoml++ license is available athttps://github.com/marzer/tomlplusplus/blob/master/LICENSE.

Thesol2 license is available athttps://github.com/ThePhD/sol2/blob/develop/LICENSE.txt.

Themagic_enum license is available athttps://github.com/Neargye/magic_enum/blob/master/LICENSE.

Contributing

Before committing, please installpre-commit,clang-format,StyLua, andPrettier, then install the pre-commit hooks. On MacOS, it would look like:

$ brew bundle# install the packages specified in Brewfile$ pre-commit install# Commit your changes.

To install pre-commit on other platforms, refer to thedocumentation.


[8]ページ先頭

©2009-2025 Movatter.jp