Library

From SolarStrike wiki
Jump to: navigation, search

cocoaAvailable

This variable is true if LuaCoco was compiled into MicroMacro, otherwise it will be false. If LuaCoco is available, then MicroMacro can take advantage of true multi-threaded co-routines, allowing it to yield across C boundaries.


Example

if( cocoAvailable ) then
  -- Coco is available! we can yield across C boundaries!
  coroutine.yield();
end


getStartKey

number getStartKey()

Returns the virtual key for the key that starts the macro.

By default, the start key is key.VK_F5, however, you can remap it to any key you want. You should not use the same key for both starting and stopping the macro.

See Virtual Keys for more information.


Example

if( getStartKey() == key.VK_F9 ) then
  -- The start key is F9
end

setStartKey

getStartKey(key)

Sets the virtual key for the key that starts the macro.

By default, the start key is key.VK_F5, however, you can remap it to any key you want. You should not use the same key for both starting and stopping the macro.

See Virtual Keys for more information.


Example

setStartKey(key.VK_F9); -- The start key is now F9

getStopKey

number getStopKey

Returns the virtual key for the key that stops the macro.

By default, it will be key.VK_F6, however, you can remap it to any key you want. You should not use the same key for both starting and stopping the macro.

See Virtual Keys for more information.


Example

printf("Stop key: %s\n", getKeyName(getStopKey()); -- Tells us that the stop key is F6 (unless changed)


setStopKey

setStopKey(key)

Sets the virtual key for the key that stops the macro.

By default, it will be key.VK_F6, however, you can remap it to any key you want. You should not use the same key for both starting and stopping the macro.

See Virtual Keys for more information.


Example

setStopKey(key.VK_F10); -- The stop key is now F10

include

include(scriptname) include(scriptname, forceInclude)

Includes (runs) whatever script is supplied. scriptname should be of type string. This is preferred over Lua's dofile(), as it will correct path issues. You may use relative paths or full paths, however, full paths are discouraged because other users may have MicroMacro or your scripts installed into another directory.

include(), by default, uses your script's 'working directory' as the base. The 'working directory' is based off of where the executing script resides. That is, if you execute the script C:/MicroMacro/scripts/myscript/main.lua, include will try to execute scripts in C:/MicroMacro/scripts/myscript/ unless told otherwise.

include() also temporarily modifies the 'working directory' to the path of the file you are including. If, for example, you include the file "C:/temp.lua", then your working directory for the duration of the execution of temp.lua will be "C:/". It will automatically return to it's prior working path after the included file has finished. Nesting of includes is allowed.

Attempting to include a file more than once will, by default, cause it to only be executed once. If you want to override this and run the file multiple times, provide true for the 'forceInclude' parameter.

Example

-- Relative path, same as working directory
include("myscript.lua");

-- Relative path, inside of another folder
include("configurations/knight.lua");

-- Relative path, back a folder
include("../baseinclude.lua");

-- Full path
include("C:/myBot/config.lua");

-- This file will NOT be run! (it has already been included)
include("myscript.lua");

-- This file WIL be run, we are forcing it to be executed
include("myscript.lua", true);

fixSlashes

fixSlashes(path) fixSlashes(path, posix)

fixSlashes() will "fix" forward/backward slashes in a string (ie. a file path) by removing duplicates that can interfere with path resolution and by converting the slashes to the proper, expected type. Generally, POSIX-style forward slashes are better to work with (and are a standard across virtually all operating systems) while Windows-style backslashes are sometimes necessary when working with Windows functions.

If 'posix' is undefined, it defaults to true, converting backslashes to forward slashes. If 'posix' is anything other than true, Windows-style backslashes will be used.

Example

path = getExecutionPath(); -- Gives us something like C:/micromacro/scripts/myscripts
newpath = fixSlashes(path, false); -- Gives us C:\micromacro\scripts\myscripts

registerTimer

registerTimer(name, time, func, ...)

registerTimer() is a shortcut to the timer functions. 'name' should be a string which you will name the timer; 'time' should be a value in miliseconds (1/1000th of a second); 'func' should be the name of the function you wish to run at the specified time interval. Any additional parameters you want to be passed to the function to be called should be used in place of vararg(...). Note that the information that will be passed to the function is the same as what is passed into registerTimer() at the time it is called, and it will not be effected if those variables changed. In order to change the information passed to the function, you will need to call registerTimer() again.

registerTimer() automatically creates, starts, and restarts the timer when needed.

Please note that you MUST make use of coroutine.yield() or yrest() in your main loop, otherwise the automatic timer related code will not get time to process.


Example

function some_function()
  print("hello!");
end


registerTimer("myTimer", 1000, some_function);
-- some_function() will now automatically be called every one second.

If you are using a function inside an object/table, you MUST pass the object/table as the first vararg(...) parameter. Example:

function MyObject:func(num)
  printf("Number is: %d\n", num);
end


registerTimer("myTimer", 1000, myObject.func, myObject, 12);

unregisterTimer

unregisterTimer(name)

Removes a timer that has been registered with registerTimer(). It will no longer be called automatically, and must be re-created or re-registered in order to use it again.


Example

unregisterTimer("myTimer");
-- myTimer will no longer be called automatically.

startMacro

startMacro(func, runstate) startMacro(func)

Starts the macro function as a coroutine. This is used to fake multi-threading so that you do not have to check for the start/stop keys, and manage registered timers. Specifying runstate is optional. If runstate is true, you will not be prompted to press the start key to start executing the script. The variable runstate is false by default.

Remember to use coroutine.yield() or yrest() within any while or for loops to give startMacro() a chance to process information.


Example

function MyMacro()
  print("This is my macro!");
end

startMacro(MyMacro);

yrest

yrest(time)

yrest(), or "yield rest", causes the script to pause for 'time' miliseconds, and automatically calls coroutine.yield() for you at 100ms intervals. It has no advantage over rest() if 'time' is less than 100 miliseconds.


Example

yrest(1000); -- rest for 1 second, and allow coroutines to run.


stopPE

stopPE()

This function will stop the protected environment, similar to when you press the stop key . Only applicable when using startMacro().

If LuaCoco is available, then stopPE() will automatically call coroutine.yield() for you. Otherwise, you will need to call coroutine.yield() yourself at an appropriate time to allow MicroMacro time to catch the stop message.

Example

if( error_has_occured ) then
  print("Some minor error has occured! Press F5 to continue anyways. ");
  stopPE();
end


printf

printf(format, ...)

printf() is a C-style glue for MicroMacro. This function will output the result to the screen. Use sprintf() if you just want to format, but not output. Many of us prefer printf-style formatting to Lua's for a number of reasons. 'format' should be of type string and use special tokens to denote data types. The most typically used tokens are:

 %s string
 %d integer (non-floating point)
 %f floating-point integer
 %x output as hexadecimal
\n new line
\t tab
\a system beep
\" A double-quotation mark (does not break string)

printf() will also accept tables, userdatas, booleans, and other Lua data types as strings, so use %s to output these types.

Also see cprintf() for outputting colored text.

Example

printf("Hello %s! My favorite number is %d, and PI is %f\n", "World", 12, 3.1415);
-- Outputs: Hello World! My favorite number is 12, and PI is 3.1415


sprintf

string sprintf(format, ...)

See printf(). This function returns the formatted string rather than printing it to the screen.


Example

formatted = sprintf("Hello %s.", "world");
print(formatted);

hoursToTimer

int hoursToTimer(hours)

Converts a time in hours to miliseconds for use in timers. Decimals are accepted. The returned value is rounded down in the chance that the result is not a whole number.


Example

registerTimer("MyTimer", hoursToTimer(0.5), MyTimer);
-- MyTimer() will be called every half hour.


minutesToTimer

int minutesToTimer(minutes)

Converts a time in minutes to miliseconds for use in timers. Decimals are accepted. The returned value is rounded down in the chance that the result is not a whole number.

See hoursToTimer().

secondsToTimer

int secondsToTimer(seconds)

Converts a time in seconds to miliseconds for use in timers. Decimals are accepted. The returned value is rounded down in the chance that the result is not a whole number.

See hoursToTimer().

atExit

atExit(function)

Sets a callback function which is called when the current script terminates. The callback function may not be called if an error occures, or MicroMacro's process terminated. That is, if you click the close button on MicroMacro's window, it will not be called. You should use CTRL + L to end the scripts properly. Pausing (pressing the stop key) does not call trigger this, as the script does not terminate.

Example

function exit_callback()
  printf("This is an example callback.\n");
end
atExit( exit_callback );


atPause

atPause(function)

Sets a callback function which is called when the current script is paused. The callback function may not be called if an error occures, or MicroMacro's process terminated. That is, if you click the close button on MicroMacro's window, it will not be called.

Example

function pause_callback()
  printf("This is an example callback.\n");
end
atPause( pause_callback );

atResume

atResume(function)

Sets a callback function which is called when the current script is resumed. The callback function may not be called if an error occures, or MicroMacro's process terminated. That is, if you click the close button on MicroMacro's window, it will not be called.

Example

function resume_callback()
  printf("This is an example callback.\n");
end
atResume( resume_callback );


atError

atError(function)

Sets a callback function which is called when the current script encounters an error. The callback function will be passed the script name, line number, and message detailing the error.

Example

function error_callback(script, line, message)
  printf("script: %s, line: %d, message: %s\n", script, line, message);
end
atError( error_callback );

colorMatch

bool colorMatch(color1, color2)

bool colorMatch(color1, color2, accuracy)

Returns true if color1 matches color2 within given accuracy, or false if they do not match. The higher 'accuracy' is, the less the two colors channels need to be alike in order to generate a match. If accuracy is not given, 0 (exact match) is assumed. 'accuracy' must be between 0 and 255 if supplied.

Example

white = makeColor(255, 255, 255);
gray = makeColor(225, 225, 225);
black = makeColor(0, 0, 0);

match = colorMatch(white, gray);      -- returns false
match = colorMatch(white, gray, 50);  -- returns true
match = colorMatch(gray, black, 50);  -- returns false
match = colorMatch(white, black);     -- returns false
match = colorMatch(white, black, 50); -- returns false

fileExists

bool fileExists(filename)


Returns true if the given file exists and is accessible. Otherwise, returns false.

Example

local fe = fileExists(getPath() .. "/scripts/myScript.lua");
if( fe == false ) then
  printf("The file does not exist or is inaccessible.\n");
end


explode

table explode(str)

table explode(str, token)


Splits 'str' into a number of strings and returns them as a table. If token is given, it will split 'str' at the given token string, otherwise it will split by spaces.

Example

local str = "This is an example string.";
local tab = explode(str, " ");
-- tab[1] now contains: This
-- tab[2] now contains: is
-- tab[3] now contains: an
-- tab[4] now contains: example
-- tab[5] now contains: string.

str = "Now, it will return a single string.";
tab = explode(str, "\t"); -- split by tab, str contains none
-- tab is now a single string, contains: Now, it will return a single string.


warning

warning(msg)

This function works almost exactly like error(), except that it does not pause script execution. It will still dump information to the log and still dump a yellow warning message to the console.


system

string system(cmd)

This allows you to run a system command and return it's output as a string. This is particularly useful for gathering information from other command-line based programs. For example, you can write scripts to interact with Image Magick or parse and make use of 'netstat' information. See the example below.


Example:

-- In this example, we will get the size of an image
-- using Image Magick's 'identify' command-line application
--
-- We tell identify to return the size in the format WxH.
-- For example: 800x600

local size = system("identify -format \"%%[width]x%%[height]\" someimage.jpg");

-- Now we've got a string like "800x600", so we use
-- a regular expression to pull the width and height
-- out of it.
local s, e, w, h = string.find(data, "(%d+)x(%d+)");
w = w or 0;
h = h or 0;

-- There we go. 'w' is now the width, and 'h' is the height.
printf("Width: %d, Height: %d\n", w, h);


createThread

createThread(name, function, ...)

Creates a named thread (ie. coroutine) that will run in the background during yields until it has ended or has been killed.

You may pass additional parameters (that will, in turn, be passed to the thread's function) if necessary.

Make sure that you are yielding within any loops in your thread.

Example

local function thread()
  while(true) do
    print("Test");
    coroutine.yield();
  end
end

createThread("test", thread);
-- Creates a thread that will continually print out "Test".



local function thread2(num)
  for i = 1,10 do
    print("Test: %d\n", num);
    coroutine.yield();
  end
end

createThread("test2", thread2, 1234);
-- Creates a thread that will continually print out "Test: 1234" 10 times then kill itself.


killThread

killThread(thread)

Kills a running thread that was created using createThread. 'thread' should be the name of the thread you want to kill.


Example

createThread("test", function () end);
killThread("test");


getThreadStatus

string getThreadStatus(thread)

Returns the status of a thread created by using createThread. The returned string will be "running", "suspended", or "dead".

When checked from within the thread, you should see "running", and from outside you will see "suspended" if the thread is still active. If the thread has finished or has been killed, it will return "dead".


Example

createThread("test", function () while(true) do coroutine.yield() end end);
local status = getThreadStatus("test");
-- status will be "suspended" -- still there, but not currently processing