Git Product home page Git Product logo

luapreprocess's Introduction

LuaPreprocess

LuaPreprocess - a small and straightforward Lua preprocessor featuring a simple syntax. Write embedded metaprograms to generate code using normal Lua inside your Lua files.

LuaPreprocess is written in pure Lua. The library is a single file with no external dependencies. MIT license. A separate command line program is available too.

Example Program

The exclamation mark (!) is used to indicate what code is part of the metaprogram. (See screenshot of processing steps with highlighting)

-- Normal Lua.
local n = 0
doSomething()

-- Preprocessor lines.
!local IS_DEVELOPER = true
initGame()
!if IS_DEVELOPER then
	enableCheats()
!else
	enableTelemetry()
!end

function newArrayOfThreeBits()
	return {
		!for i = 1, 3 do
			0,
		!end
	}
end

-- Extended preprocessor line. (Lines are consumed until brackets
-- are balanced when the end of the line is reached.)
!defineClass{
	name  = "Entity",
	props = {x=0, y=0},
}

-- Preprocessor block.
!(
local hashLib = require("md5")
function getHash()
	return hashLib.calculate("Hello, world!")
end
)

-- Preprocessor inline block. (Expression that returns a value.)
local text = !("Precalculated hash: "..getHash())

-- Preprocessor inline block variant. (Expression that returns a Lua code string.)
!!("myRandomGlobal"..math.random(9)) = "foo"

Output

-- Normal Lua.
local n = 0
doSomething()

-- Preprocessor lines.
initGame()
enableCheats()

function newArrayOfThreeBits()
	return {
		0,
		0,
		0,
	}
end

-- Extended preprocessor line. (Lines are consumed until brackets
-- are balanced when the end of the line is reached.)
function newEntity() return {__name="Entity",x=0,y=0} end

-- Preprocessor block.

-- Preprocessor inline block. (Expression that returns a value.)
local text = "Precalculated hash: 6CD3556DEB0DA54BCA060B4C39479839"

-- Preprocessor inline block variant. (Expression that returns a Lua code string.)
myRandomGlobal4 = "foo"

See the examples folder for more. (See also an example for the LÖVE framework.)

Usage

First you need Lua installed on your system. (Binaries can be downloaded from LuaBinaries via SourceForge if you don't want to, or can't, compile Lua from source. For Windows I can recommend installing LuaForWindows which is a "batteries included" Lua package.)

Preprocess Files Using the Library

local pp = require("preprocess")

local info, err = pp.processFile{
	pathIn   = "src/app.lua2p",     -- This is the file we want to process.
	pathOut  = "output/app.lua",    -- The output path.
	pathMeta = "temp/app.meta.lua", -- Temporary output file for the metaprogram.
}

if not info then
	error(err)
end

print("Lines of code processed: "..info.lineCount)

See the website or the top of preprocess.lua for documentation.

Preprocess Files from the Command Line

Windows

Preprocess.cmd [options] filepath1 [filepath2 ...]
OR
Preprocess.cmd --outputpaths [options] inputpath1 outputpath1 [inputpath2 outputpath2 ...]

Any System

lua preprocess-cl.lua [options] filepath1 [filepath2 ...]
OR
lua preprocess-cl.lua --outputpaths [options] inputpath1 outputpath1 [inputpath2 outputpath2 ...]

If a filepath is, for example, C:/MyApp/app.lua2p then LuaPreprocess will write the processed file to C:/MyApp/app.lua.

See the website, or the top of preprocess-cl.lua and preprocess.lua, for the options and more documentation.

Documentation

Help

Got a question? If the documentation doesn't have the answer, look if someone has asked the question in the issue tracker, or create a new issue.

Also check out the online syntax highlighter tool to help visualize errors in code.

luapreprocess's People

Contributors

refreezed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

luapreprocess's Issues

Help with outputting modified string value

I have a handler.lua with:

_C_HSPEED = toLua("hspeed")

Which i use like local component = $_C_HSPEED.

However, I also need to have something with ! prefix like : local n = "!hspeed"

Ive tried:

--handler.lua
function n(component) return "!" .. component end

with @@n($_C_HSPEED) but it complains about the ! token as it outputs !"hspeed" literally.

And yes, "!" .. $_C_HSPEED works as it generates "!" .. "hspeed" in the output file but this would be the last resort if no other way is possible

Malformed string

Hi, parsing something this results to malformed string error

local error_msg = format("Data integrity is not valid.\n
				Please do not modify the files: '%s' and '%s'.\n
				Please delete the files in '%s' and restart the game",
				save_filename, key_filename, love.filesystem.getSaveDirectory())

Here's the output:

==============================================
= LuaPreprocess v1.11.0, 2020-08-09 12:08:54 =
==============================================
Processing 'test.lua2p'...
Error @ test.lua2p:1: [Tokenizer] Malformed string.
>
> local error_msg = format("Data integrity is not valid.\n
>--------------------------^
>

Making the string one-liner doesn't result to the error.

Error catching for build scripts;

Hi, I am wondering if the lib already allows returning error code when a file can't be parsed (instead of just showing an error message)

My use case is that for my bash script, I want to catch that error and not continue running my build script if an error occurred.

require inside handler file not working

Hi, im doing some separation for my different builds. I have handler_dev.lua and handler_test.lua that I use depending on what I want to build.

Content of handler_dev.lua:

_RELEASE = false
_REPORTING = false
_NETWORK = false
_ASSERT = true
_LOG_SAVE = false

require("handler")
return {}

Content of handler_test.lua:

_RELEASE = true
_REPORTING = false
_NETWORK = false
_ASSERT = false
_LOG_SAVE = false

require("handler")
return {}

Now, handler.lua is a file that contains all other metadata I need that is common to both of them, like:

_PLATFORM = "desktop"
_GAME_TITLE  = "project name"
_GAME_SIZE = { x = 1024, y = 640 }
_GAME_BASE_SIZE = { x = 128, y = 32 }

_IDENTITY = "projectname"
_LOVE_VERSION = "11.3"
_GAME_VERSION = { 0, 0, 1 }

But having the require gives this error:
Error @ output//error_handler.lua:139: 'end' expected (to close 'if' at line 134) near 'if'

Issue with requiring files with .lua2p extension

Hi, still tinkering with this awesome lib when I've found out that

--src/main.lua2p
local test_module
!if _DEBUG then
test_module = require("src.test_module") --"src/test_module" does not work either
!end

--src/test_modules.lua2p
local test_module = {}
!if _DEBUG then
print(1)
!else
print(2)
!end
return test_module = {}

error is that src/test_module could not be found.

Does this mean that I have change all required modules that use src/** to use srcgen/** ?

`outputLua` errors if string has `@@`

example:

!(
local ids = {
	"typewriter",
}
for _, v in ipairs(ids) do
	local cname = v .. "_on_finish"
	outputLua("Concord.component('" .. cname .. "', function(c, signal, delay, ...)\n")
	outputLua("\t@@assert(type(signal) == 'string')\n")
	outputLua("\t@@assert(type(delay) == 'delay')\n")
	outputLua("\tc.signal = signal\n")
	outputLua("\tc.delay = delay or 0\n")
	outputLua("\tc.args = {...}\n")
	outputLua("end)\n\n")
end
)

(removing the line with @@ works)
The desired generated code is:

Concord.component('typewriter_on_finish', function(c, signal, delay, ...)
	@@assert(type(signal) == 'string')
	@@assert(type(delay) == 'delay')
	c.signal = signal
	c.delay = delay or 0
	c.args = {...}
end)

the @@assert is a function defined in the handler.lua:

function assert(cond, msg)
	if _RELEASE then return "" end
	msg = msg or string.format("%q", "Assertion failed: " .. cond)
	return "if not (" .. cond .. ") then error(" .. msg ..") end"
end

the error is unexpected symbol near '@'

Pass string to cmd version

I'm wondering why there's nothing like
lua preprocess-cmd.lua input.lua output.lua -isdebug

It would be useful and more appropriate for usage to be able to pass meta information than to make a build system like the one in your löve's example (also check the comment I've made there)

I have looked at the examples and the lua file itself. I may have missed it.

Sent from my HUAWEI GR5 2017 using FastHub

Pass output path for cli

does this already have something like this? Ive checked the wiki and havent found anything for it.

lua preprocess-cl.lua --handler=myHandler.lua src/main.lua2p ../output/src/

How can I implement the following functionality?

Hello, I would like to implement a macro definition feature similar to C++. Here is an example code. Could you please guide me on how to achieve this?

#define GIsShipping

#if GIsShipping then
    #define Log(...) Log(...)
#else
    #define Log(...) 
#endif

Allowing multiple values in !(...)

--color.lua
local function convert(r, g, b)
  return r/255, g/255, b/255 --it seems that only the r/255 is returned
end
--main/lua
!(@insert "color.lua")

local test = { !(convert(255, 255, 255)) }
print(unpack(test)) --prints only 1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.