Skip to content

Commit 8a6d8f6

Browse files
committed
Python 3.11+ compatibility
1 parent 1228580 commit 8a6d8f6

1 file changed

Lines changed: 22 additions & 8 deletions

File tree

src/pythoninlua.c

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,8 @@ static int py_object_call(lua_State *L)
184184
ret = py_convert(L, value);
185185
Py_DECREF(value);
186186
} else {
187-
char s_exc[1024] = {0};
188-
char s_traceback[1024] = {0};
187+
char s_exc[4096] = {0};
188+
char s_traceback[sizeof(s_exc)] = {0};
189189

190190
PyObject *exc_type, *exc_value, *exc_traceback;
191191
PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);
@@ -195,7 +195,7 @@ static int py_object_call(lua_State *L)
195195

196196
// Need not be garbage collected as per documentation of PyUnicode_AsUTF8
197197
const char *exc_cstr = (exc_str)?PyUnicode_AsUTF8(exc_str):"";
198-
strncpy(s_exc, (!(exc_cstr)?"UNKNOWN ERROR\n":exc_cstr), 1023);
198+
strncpy(s_exc, (!(exc_cstr)?"UNKNOWN ERROR\n":exc_cstr), sizeof(s_exc)-1);
199199

200200
if (exc_value != NULL && exc_traceback != NULL) {
201201
PyObject *traceback_module = PyImport_ImportModule("traceback");
@@ -208,7 +208,7 @@ static int py_object_call(lua_State *L)
208208
// Need not be garbage collected as per documentation of PyUnicode_AsUTF8
209209
const char *traceback_cstr = PyUnicode_AsUTF8(traceback_str);
210210
if (traceback_cstr != NULL) {
211-
strncpy(s_traceback, traceback_cstr, 1023);
211+
strncpy(s_traceback, traceback_cstr, sizeof(s_exc)-1);
212212
}
213213
Py_XDECREF(traceback_str);
214214
}
@@ -665,12 +665,25 @@ LUA_API int luaopen_python(lua_State *L)
665665
if (!Py_IsInitialized())
666666
{
667667
PyObject *luam, *mainm, *maind;
668+
#if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 11)
669+
// Python 3.11+ syntax
670+
char *argv[] = {"python3", 0};
671+
672+
PyConfig config;
673+
PyConfig_InitPythonConfig(&config);
674+
config.isolated = 1;
675+
676+
PyConfig_SetBytesArgv(&config, 1, argv);
677+
#else
668678
#if PY_MAJOR_VERSION >= 3
669-
wchar_t *argv[] = {L"<lua>", 0};
679+
// Python < 3.11 syntax
680+
wchar_t *argv[] = {L"python3", 0};
670681
#else
671-
char *argv[] = {"<lua>", 0};
682+
// Python 2 syntax
683+
char *argv[] = {"python2", 0};
672684
#endif
673685
Py_SetProgramName(argv[0]);
686+
#endif
674687
PyImport_AppendInittab("lua", PyInit_lua);
675688

676689
/* Loading python library symbols so that dynamic extensions don't throw symbol not found error.
@@ -686,8 +699,9 @@ LUA_API int luaopen_python(lua_State *L)
686699
assert(ok); (void) ok;
687700
#endif
688701

689-
Py_Initialize();
690-
PySys_SetArgv(1, argv);
702+
Py_InitializeFromConfig(&config);
703+
PyConfig_Clear(&config);
704+
691705
/* Import 'lua' automatically. */
692706
luam = PyImport_ImportModule("lua");
693707
if (!luam)

0 commit comments

Comments
 (0)