Gravity is a powerful, dynamically typed, lightweight, embeddable programming language. It is a class-based concurrent scripting language with a modern Swift like syntax.
Gravity for Swift is a Swift Package that allows you to use the Gravity language with your Swift projects.
This README does not cover the Gravity language.
Before jumping in you should familiarize yourself with Gravity's documentation.
You can add Gravity for Swift to a package:
let package = Package(
name: "MyThing",
dependencies: [
// Add Gravity as a package dependency so it's available to your target
.package(url: "https://github.com/STREGAsGate/Gravity.git", branch: "master"),
],
targets: [
// Add Gravity to your target dependencies
// This will make Gravity available to `import Gravity`
.executableTarget(name: "MyThing", dependencies: ["Gravity"]),
]
)
If you are using an Xcode Project you can add gravity by selecting your project in the navigator, your project at the top of the targets list, and finally the Package Dependencies tab.
import Gravity
// The Gravity object handles everything.
let gravity = Gravity()
// Compile script from a URL
let bundleURL = Bundle.module.resourceURL!
let scriptURL = bundleURL.appendingPathComponent("File.gravity")
try gravity.compile(scriptURL)
// Execute the script's func main()
try gravity.runMain()
A Gravity script can also be compiled from a string.
try gravity.compile("func main() {}")
Some actions must be done in a specific order.
For example, you cannot call runMain()
before calling compile(script)
.
You can retrieve a value from the script in various ways.
A global variable is any variable in the root of a script.
/* --- Gravity Script --- */
var myVar = 10 // <- This is a global variable
func main() {}
You can obtain the value of a global variable using gravity.getVar("myVar")
.
// The GravityValue type is the universal return type for Gravity
let myVarGravity: GravityValue = gravity.getVar("myVar")
// Make sure it's an Int
assert(myVarGravity.valueType == .int)
// Ask for the Int
let myVar: Int = myVarGravity.getInt()
// The Int can also be obtained directly by declarting myVar as an Int
let myVar: Int = gravity.getVar("myVar")
All Closures in Gravity return a value, but you can ignore the value if you know it's empty
// Ignoring the return value
try gravity.runMain()
// Storing the return value
let result = try gravity.runMain()
You can access the unmodifed c99 Gravity source directly via the Swift module GravityC.
import GravityC
Note: Using the GravityC module requires significant knowledge of Swift's Unsafe API and is not recommended.
Check out what I'm working on at various places or come say hi on discord!