Skip to content

Instantly share code, notes, and snippets.

@nokotan
Last active July 8, 2021 04:43
Show Gist options
  • Save nokotan/aab0bae4a954c6639e7c81eb8a794a92 to your computer and use it in GitHub Desktop.
Save nokotan/aab0bae4a954c6639e7c81eb8a794a92 to your computer and use it in GitHub Desktop.
#include <emscripten.h>
#include <functional>
#include <numeric>
#include <cassert>
#include <iostream>
std::function<void()> mainLoop;
void runMainLoop()
{
mainLoop();
}
void userMain()
{
// allocate someData onto the stack
int someData[100]; // [ 0, 1, , ... , 99 ]
std::iota(std::begin(someData), std::end(someData), 0);
// Check values in someData
for (int i = 0; i < 100; i++)
{
std::cout << someData[i] << std::endl;
assert(someData[i] == i);
}
mainLoop = [&]()
{
// someData is captured by lambda, so we can use it here.
// Some works here on the stack
{
int anyData[100]; // [ 99, 98, ... , 0 ]
std::iota(std::rbegin(anyData), std::rend(anyData), 0);
}
// Any operations with the stack should not affect someData in this lambda
// let's check values in someData
for (int i = 0; i < 100; i++)
{
std::cout << someData[i] << std::endl;
assert(someData[i] == i);
}
::emscripten_cancel_main_loop();
};
::emscripten_set_main_loop(&runMainLoop, 0, true);
}
int main()
{
try
{
userMain();
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment