A single API across many different platforms

So here’s an idea I’m hoping I can implement with Haxe. First up let me say I’ve been curious about haxe since its release as an alternative to Flash. Secondly I think you guys have built a fantastic toolset which deserves way more attention from the community!

Lets say I have a simple function that I want to build, which saves a string to a file. Can I define platform-specific code for it like this?

void SaveStringToFile(text:String, path:String){ 
	if (platform == "php"){
		file_put_contents(path, text);
	}
	if (platform == "cs"){
		File.WriteAllText(path, text);
	}
	if (platform == "nodejs"){
		fs.writeFile(path, text);
	}
}

What I’m hoping to do is build an application that can be seamlessly compiled to various platforms. And I’m hoping that Haxe will let me do that.

You can using conditional compilation:

function SaveStringToFile(text:String, path:String):Void{ 
	#if php
		file_put_contents(path, text);
	#elseif cs
		File.WriteAllText(path, text);
	#elseif nodejs
		fs.writeFile(path, text);
	#end
}
2 Likes

Or in this particular case simply use a cross-platform API provided by the Haxe standard library sys.io.File.saveContent(path, text)

3 Likes